Skip to main content

relate_model/
wire.rs

1//! Canonical JSON **wire** encoding shared by every Relate surface.
2//!
3//! This module is the single source of truth for how a [`CypherValue`], a set
4//! of mutation counters, and a query response are rendered as JSON on the wire
5//! (the C FFI, the CLI, and the shapes the language bindings derive from
6//! those). Every surface is expected to route its serialization
7//! through here so that a drift in one surface becomes a failing golden test
8//! (see the [`golden`] submodule).
9//!
10//! It is deliberately distinct from the persistence encoding in
11//! [`crate::serde_value`] (the `__type`-tagged format used for on-disk
12//! round-tripping and for `CypherValue`'s `serde::Serialize` impl). The wire
13//! encoding is **self-describing and stable**: it never falls through to a
14//! `Display` string for a structured value, and is documented field-by-field
15//! below. Entity values (nodes and relationships) carry an explicit
16//! `"kind"` discriminator so clients dispatch on a
17//! documented field instead of sniffing key sets (ADR-0223, a breaking wire
18//! change recorded in the CHANGELOG); the `__type`-tagged persistence
19//! format remains a separate encoding.
20//!
21//! # Value encoding ([`value_to_wire_json`])
22//!
23//! | Variant | Wire JSON |
24//! |---|---|
25//! | `Null` | `null` |
26//! | `Bool` | `true` / `false` |
27//! | `Int` | JSON integer |
28//! | `Float` | JSON number (non-finite `NaN`/`±Inf` → `"NaN"`/`"Inf"`/`"-Inf"`, see below) |
29//! | `Str` | JSON string |
30//! | `List` | JSON array (elements recursively encoded) |
31//! | `Map` | JSON object (values recursively encoded) |
32//! | `Node` | `{"kind":"node","id","labels","properties"}` |
33//! | `Relationship` | `{"kind":"relationship","id","type","start_node","end_node","properties"}` |
34//! | `Path` | JSON array alternating `[node, rel, node, rel, …, node]` (no tag of its own; elements carry their `kind`, ADR-0223) |
35//! | `Date` | ISO-8601 date string `YYYY-MM-DD` |
36//! | `Time` | ISO-8601 time string `HH:MM[:SS[.fff]][±HH:MM[:SS] or Z]` |
37//! | `DateTime` | ISO-8601 `YYYY-MM-DDTHH:MM:SS[.fff]±HH:MM[[Zone/Id]]` |
38//! | `LocalDateTime` | ISO-8601 `YYYY-MM-DDTHH:MM:SS[.fff]` |
39//! | `Duration` | ISO-8601 duration `PnYnMnDTnHnMnS` |
40//! | `Point` | coordinate-key object + `srid`/`crs` marker (below) |
41//! | `Geometry` | GeoJSON-style `{"type", "coordinates" or "geometries"}` |
42//! | `Vector` | `{"type","dim","values"}` (structured, **not** a string) |
43//!
44//! The five temporal renderings are exactly the canonical ISO-8601 `Display`
45//! forms of the corresponding `CypherValue` (trailing-zero-trimmed fractional
46//! seconds, compact offsets, `Z` for UTC, `[IANA/Zone]` suffix on a zoned
47//! `DateTime`). They are unambiguous and parseable, and — unlike the
48//! persistence format — carry no type tag.
49//!
50//! ## Point (`Point`)
51//!
52//! A coordinate-key object carrying an explicit CRS marker so the reader never
53//! has to guess the coordinate space:
54//! - geographic (`srid` 4326 / 4979): `{"srid","crs","longitude","latitude"[,"height"]}`
55//! - cartesian (all other srids): `{"srid","crs","x","y"[,"z"]}`
56//!
57//! `crs` is the Neo4j CRS name (`wgs-84`, `wgs-84-3d`, `cartesian`,
58//! `cartesian-3d`; unknown srids fall back to `cartesian` keys/name). The
59//! `srid`/`crs` marker is new relative to the historical CLI/WASM point output,
60//! which emitted the coordinate keys alone.
61//!
62//! ## Vector (`Vector`)
63//!
64//! `{"type": <coordinate-type name>, "dim": <usize>, "values": [<number>, …]}`.
65//! `type` is the canonical coordinate-type name (`INTEGER8`, `INTEGER16`,
66//! `INTEGER32`, `INTEGER`, `FLOAT32`, `FLOAT`); integer-kind vectors carry JSON
67//! integers, float-kind vectors carry JSON numbers. This replaces the previous
68//! bug where every surface stringified a vector via `Display`
69//! (`vector([…], 3, FLOAT32 NOT NULL)`).
70//!
71//! ## Non-finite floats
72//!
73//! `NaN`, `+Inf`, and `-Inf` are not representable as standard JSON numbers
74//! and are encoded as the JSON strings `"NaN"`, `"Inf"`, and `"-Inf"` —
75//! exactly the `CypherValue` `Display` spellings, so the JSON surfaces agree
76//! with the table/CSV modes and a non-finite float is never
77//! indistinguishable from a genuine `null` (ADR-0280; a breaking wire
78//! change from the previous `null` encoding, acceptable pre-1.0/alpha per
79//! the precedent below, recorded in the CHANGELOG).
80//!
81//! # Stats encoding ([`stats_to_wire_json`])
82//!
83//! All **11** mutation counters, **snake_case**, **zeros included**:
84//!
85//! `nodes_created`, `nodes_deleted`, `relationships_created`,
86//! `relationships_deleted`, `properties_set`, `labels_added`, `labels_removed`,
87//! `indexes_added`, `indexes_removed`, `constraints_added`,
88//! `constraints_removed`.
89//!
90//! [`stats_from_wire_json`] is the inverse: it decodes that object back into
91//! a [`WireStatsSnapshot`], naming the first canonical counter that is
92//! missing or not an unsigned integer.
93//!
94//! These are the canonical names (they match the engine's `Stats` field names
95//! and Neo4j's `Added`/`Removed` semantics). The historical JSONL server
96//! renamed four of them (`indexes_added`→`indexes_created`,
97//! `indexes_removed`→`indexes_dropped`, and the two `constraints_*`
98//! equivalents); the WASM surface used camelCase and omitted zeros; the FFI
99//! surface emitted only six. Unifying on this set is a breaking wire change
100//! (documented in the CHANGELOG; acceptable pre-1.0/alpha).
101//!
102//! # Response envelope ([`response_envelope`] / [`error_envelope`])
103//!
104//! ```json
105//! { "columns": [ … ], "columnTypes": [ … ], "rows": [ { … }, … ], "stats": { … }, "notifications": [ … ], "elapsed_ms": 1.25, "parse_ms": 0.4, "plan_ms": 1.1, "execute_ms": 10.8, "plan_cache": "<outcome>", "error": null, "plan": { … } | null }
106//! ```
107//!
108//! Object members serialize in the construction order shown here
109//! (ADR-0634): a row object's keys follow the statement's column order,
110//! and every wire object follows its documented order. JSON objects are
111//! formally unordered — consumers match by key name, and `columns`
112//! stays the authoritative column order — but the byte stream no longer
113//! contradicts the documented shapes.
114//!
115//! `notifications` is always present and empty on a plain run (ADR-0363
116//! decision 9); its entries are the engine-native notification objects
117//! ([`notification_to_wire_json`]). `plan` is always present too — the
118//! `relate.plan/v1` document (LABS-418, ADR-0381), `null` on a plain
119//! run.
120//!
121//! The row container key is **`rows`**. The historical JSONL server and FFI
122//! used `data`; migrating them to `rows` is part of the same unification.
123//! `elapsed_ms` is the engine-reported statement elapsed in wall-clock
124//! milliseconds (ADR-0221). `parse_ms`/`plan_ms`/`execute_ms` are that
125//! window's PARSE / PLAN / EXECUTE split (ADR-0491): always-on, disjoint
126//! sub-windows whose sum never exceeds `elapsed_ms` (the inter-stage gaps
127//! stay in the total alone). The total and its split ride the builder
128//! together as one [`TimingStampMs`] — an envelope construction site
129//! cannot carry the total without its split.
130//! `columnTypes` carries the engine-stamped
131//! per-column type names of ADR-0224 (one of the 18 canonical names, beside
132//! `columns`, same length and order; a column whose first-row value is
133//! `Null`, or a result with no rows, stamps `ANY`, so a write-only envelope
134//! carries `"columnTypes": []`). On error: `columns: []`, `rows: []`,
135//! `stats: {}`, `error: <message string>` (no `elapsed_ms`: no statement
136//! ran).
137
138use std::borrow::Cow;
139
140use indexmap::IndexMap;
141use serde_json::{Map, Value};
142
143use crate::point::{is_geographic, point_axis_keys};
144use crate::value::{CypherValue, GeometryValue, PointValue};
145use crate::vector::coords::Coord;
146
147/// The `kind` discriminator of a wire node object (ADR-0223). Decoder sides
148/// match on these constants instead of re-typing the literals.
149pub const WIRE_KIND_NODE: &str = "node";
150
151/// The `kind` discriminator of a wire relationship object (ADR-0223).
152pub const WIRE_KIND_RELATIONSHIP: &str = "relationship";
153
154/// Encode a [`CypherValue`] as its canonical wire JSON.
155///
156/// Covers all 18 variants with structured, self-describing encodings; no
157/// variant falls through to a `Display` string except the five temporal
158/// variants, whose ISO-8601 string *is* the canonical encoding. See the module
159/// docs for the full table.
160pub fn value_to_wire_json(val: &CypherValue) -> Value {
161    match val {
162        CypherValue::Null => Value::Null,
163        CypherValue::Bool(b) => Value::Bool(*b),
164        CypherValue::Int(i) => Value::Number((*i).into()),
165        CypherValue::Float(f) => json_f64(*f),
166        CypherValue::Str(s) => Value::String(s.clone()),
167        CypherValue::List(items) => Value::Array(items.iter().map(value_to_wire_json).collect()),
168        CypherValue::Map(map) => Value::Object(map_to_wire_json(map)),
169        CypherValue::Node {
170            id,
171            labels,
172            properties,
173        } => {
174            let mut obj = Map::new();
175            // ADR-0223: the `kind` discriminator lets clients dispatch on a
176            // documented field instead of shape-sniffing.
177            obj.insert("kind".into(), Value::String(WIRE_KIND_NODE.into()));
178            obj.insert("id".into(), Value::Number((*id).into()));
179            obj.insert(
180                "labels".into(),
181                Value::Array(labels.iter().map(|l| Value::String(l.clone())).collect()),
182            );
183            obj.insert(
184                "properties".into(),
185                Value::Object(map_to_wire_json(properties)),
186            );
187            Value::Object(obj)
188        }
189        CypherValue::Relationship {
190            id,
191            start_id,
192            end_id,
193            rel_type,
194            properties,
195        } => {
196            let mut obj = Map::new();
197            // ADR-0223: see the `Node` arm.
198            obj.insert("kind".into(), Value::String(WIRE_KIND_RELATIONSHIP.into()));
199            obj.insert("id".into(), Value::Number((*id).into()));
200            obj.insert("type".into(), Value::String(rel_type.clone()));
201            obj.insert("start_node".into(), Value::Number((*start_id).into()));
202            obj.insert("end_node".into(), Value::Number((*end_id).into()));
203            obj.insert(
204                "properties".into(),
205                Value::Object(map_to_wire_json(properties)),
206            );
207            Value::Object(obj)
208        }
209        CypherValue::Path {
210            nodes,
211            relationships,
212        } => {
213            // Alternating [node, rel, node, rel, …, node]. A well-formed path
214            // has `nodes.len() == relationships.len() + 1`, so the trailing
215            // node emits no following relationship.
216            let mut items = Vec::with_capacity(nodes.len() + relationships.len());
217            for (i, n) in nodes.iter().enumerate() {
218                items.push(value_to_wire_json(n));
219                if let Some(r) = relationships.get(i) {
220                    items.push(value_to_wire_json(r));
221                }
222            }
223            Value::Array(items)
224        }
225        // Temporal values: canonical ISO-8601 Display strings (documented,
226        // stable, and tag-free). This is the one intentional "Display" arm.
227        CypherValue::Date(_)
228        | CypherValue::Time(_, _)
229        | CypherValue::DateTime(_, _)
230        | CypherValue::LocalDateTime(_)
231        | CypherValue::Duration(_) => Value::String(val.to_string()),
232        CypherValue::Point(p) => point_to_wire_json(p),
233        CypherValue::Geometry(g) => geometry_to_wire_json(g),
234        CypherValue::Vector { coord, coords } => {
235            let mut obj = Map::new();
236            obj.insert(
237                "type".into(),
238                Value::String(coord.canonical_name().to_string()),
239            );
240            obj.insert("dim".into(), Value::Number((coords.len() as u64).into()));
241            obj.insert(
242                "values".into(),
243                Value::Array(
244                    // The packed read (ADR-0706): each coordinate encodes
245                    // exactly as the `Int`/`Float` value it replaced.
246                    coords
247                        .iter()
248                        .map(|c| match c {
249                            Coord::I(n) => Value::Number(n.into()),
250                            Coord::F(f) => json_f64(f),
251                        })
252                        .collect(),
253                ),
254            );
255            Value::Object(obj)
256        }
257    }
258}
259
260/// Encode a property/value map (used for node & relationship `properties` and
261/// for `CypherValue::Map`).
262fn map_to_wire_json(map: &IndexMap<String, CypherValue>) -> Map<String, Value> {
263    map.iter()
264        .map(|(k, v)| (k.clone(), value_to_wire_json(v)))
265        .collect()
266}
267
268/// Encode an `f64` as wire JSON: a JSON number when finite, otherwise the
269/// JSON string of its `CypherValue` `Display` spelling (`"NaN"`/`"Inf"`/
270/// `"-Inf"`, ADR-0280).
271pub fn json_f64(f: f64) -> Value {
272    serde_json::Number::from_f64(f)
273        .map(Value::Number)
274        .unwrap_or_else(|| Value::String(CypherValue::Float(f).to_string()))
275}
276
277/// The Neo4j CRS name for an SRID (used as the `crs` point marker) — the
278/// canonical mapping every surface shares (ADR-0280 wire shape).
279pub fn crs_name(srid: i32) -> &'static str {
280    match srid {
281        4326 => "wgs-84",
282        4979 => "wgs-84-3d",
283        7203 => "cartesian",
284        9157 => "cartesian-3d",
285        _ => "cartesian",
286    }
287}
288
289fn point_to_wire_json(p: &PointValue) -> Value {
290    let mut obj = Map::new();
291    obj.insert("srid".into(), Value::Number(p.srid.into()));
292    obj.insert("crs".into(), Value::String(crs_name(p.srid).to_string()));
293    // Geographic and cartesian differ only in the coordinate key names,
294    // which are the shared axis vocabulary's two spellings.
295    let [x_key, y_key, z_key] = point_axis_keys(is_geographic(p.srid));
296    obj.insert(x_key.into(), json_f64(p.x));
297    obj.insert(y_key.into(), json_f64(p.y));
298    if let Some(z) = p.z {
299        obj.insert(z_key.into(), json_f64(z));
300    }
301    Value::Object(obj)
302}
303
304fn coords_to_wire_json(coords: &[[f64; 2]]) -> Value {
305    Value::Array(
306        coords
307            .iter()
308            .map(|c| Value::Array(vec![json_f64(c[0]), json_f64(c[1])]))
309            .collect(),
310    )
311}
312
313fn geometry_to_wire_json(g: &GeometryValue) -> Value {
314    let mut obj = Map::new();
315    obj.insert("type".into(), Value::String(g.type_name().to_string()));
316    match g {
317        GeometryValue::LineString { coordinates, .. } => {
318            obj.insert("coordinates".into(), coords_to_wire_json(coordinates));
319        }
320        GeometryValue::Polygon { rings, .. } => {
321            obj.insert(
322                "coordinates".into(),
323                Value::Array(rings.iter().map(|r| coords_to_wire_json(r)).collect()),
324            );
325        }
326        GeometryValue::MultiPoint { points, .. } => {
327            obj.insert("coordinates".into(), coords_to_wire_json(points));
328        }
329        GeometryValue::MultiLineString { lines, .. } => {
330            obj.insert(
331                "coordinates".into(),
332                Value::Array(lines.iter().map(|l| coords_to_wire_json(l)).collect()),
333            );
334        }
335        GeometryValue::MultiPolygon { polygons, .. } => {
336            obj.insert(
337                "coordinates".into(),
338                Value::Array(
339                    polygons
340                        .iter()
341                        .map(|poly| {
342                            Value::Array(poly.iter().map(|r| coords_to_wire_json(r)).collect())
343                        })
344                        .collect(),
345                ),
346            );
347        }
348        GeometryValue::GeometryCollection { geometries, .. } => {
349            obj.insert(
350                "geometries".into(),
351                Value::Array(geometries.iter().map(geometry_to_wire_json).collect()),
352            );
353        }
354    }
355    Value::Object(obj)
356}
357
358/// Encode one result row (an ordered column→value map) as a JSON object.
359///
360/// Columns are taken from `columns` (preserving the query's column order in the
361/// underlying ordered map); a column absent from `row` encodes as `null`.
362pub fn row_to_wire_json(columns: &[String], row: &IndexMap<String, CypherValue>) -> Value {
363    let mut obj = Map::new();
364    for col in columns {
365        let v = row.get(col).map(value_to_wire_json).unwrap_or(Value::Null);
366        obj.insert(col.clone(), v);
367    }
368    Value::Object(obj)
369}
370
371/// Build the canonical wire `rows` array for a query result.
372///
373/// This is the single, shared assembly point for the row container so the
374/// JSON surfaces (C FFI, CLI) cannot diverge on it. It applies
375/// the **write-only rule**: a statement that produces no result columns (a
376/// `CREATE`/`MERGE`/`SET`/… without `RETURN`) yields an empty `rows` array — not
377/// a `[{}]` array of empty objects — even though the engine emits one driving
378/// row per input row (seeded with a single empty row for a top-level write).
379/// When there are columns, each row is encoded via [`row_to_wire_json`].
380///
381/// Historically only the JSONL server guarded the empty-columns case; the FFI
382/// and WASM surfaces mapped every driving row unconditionally and so emitted
383/// `[{}]` for a write-only statement. Routing all three through this helper
384/// makes that drift structurally impossible (pinned by
385/// [`golden::envelope_write_only`]).
386pub fn rows_for_result(columns: &[String], rows: &[IndexMap<String, CypherValue>]) -> Vec<Value> {
387    if columns.is_empty() {
388        Vec::new()
389    } else {
390        rows.iter()
391            .map(|row| row_to_wire_json(columns, row))
392            .collect()
393    }
394}
395
396/// The 11 canonical mutation counters, read as `u64`.
397///
398/// Implemented by [`WireStatsSnapshot`] here (built from the executor's
399/// `QueryStats` via `relate::query_stats_to_wire`), so
400/// `stats_to_wire_json` can serialize either without `relate-model`
401/// depending on the executor.
402pub trait WireStats {
403    fn nodes_created(&self) -> u64;
404    fn nodes_deleted(&self) -> u64;
405    fn relationships_created(&self) -> u64;
406    fn relationships_deleted(&self) -> u64;
407    fn properties_set(&self) -> u64;
408    fn labels_added(&self) -> u64;
409    fn labels_removed(&self) -> u64;
410    fn indexes_added(&self) -> u64;
411    fn indexes_removed(&self) -> u64;
412    fn constraints_added(&self) -> u64;
413    fn constraints_removed(&self) -> u64;
414}
415
416/// A plain, model-owned carrier of the 11 counters — a [`WireStats`] value that
417/// does not require the engine crate (used by the golden fixtures and by any
418/// surface that already has counts in hand).
419#[derive(Debug, Clone, Default, PartialEq, Eq)]
420pub struct WireStatsSnapshot {
421    pub nodes_created: u64,
422    pub nodes_deleted: u64,
423    pub relationships_created: u64,
424    pub relationships_deleted: u64,
425    pub properties_set: u64,
426    pub labels_added: u64,
427    pub labels_removed: u64,
428    pub indexes_added: u64,
429    pub indexes_removed: u64,
430    pub constraints_added: u64,
431    pub constraints_removed: u64,
432}
433
434impl WireStats for WireStatsSnapshot {
435    fn nodes_created(&self) -> u64 {
436        self.nodes_created
437    }
438    fn nodes_deleted(&self) -> u64 {
439        self.nodes_deleted
440    }
441    fn relationships_created(&self) -> u64 {
442        self.relationships_created
443    }
444    fn relationships_deleted(&self) -> u64 {
445        self.relationships_deleted
446    }
447    fn properties_set(&self) -> u64 {
448        self.properties_set
449    }
450    fn labels_added(&self) -> u64 {
451        self.labels_added
452    }
453    fn labels_removed(&self) -> u64 {
454        self.labels_removed
455    }
456    fn indexes_added(&self) -> u64 {
457        self.indexes_added
458    }
459    fn indexes_removed(&self) -> u64 {
460        self.indexes_removed
461    }
462    fn constraints_added(&self) -> u64 {
463        self.constraints_added
464    }
465    fn constraints_removed(&self) -> u64 {
466        self.constraints_removed
467    }
468}
469
470/// Encode the 11 canonical mutation counters as a JSON object: snake_case keys,
471/// zeros included. See the module docs for the canonical name set.
472pub fn stats_to_wire_json(stats: &dyn WireStats) -> Value {
473    Value::Object(
474        STAT_COUNTERS
475            .iter()
476            .map(|counter| (counter.key.to_string(), (counter.count)(stats).into()))
477            .collect(),
478    )
479}
480
481/// Decode an envelope's `stats` object into the 11 canonical counters — the
482/// inverse of [`stats_to_wire_json`], reading the same [`STAT_COUNTERS`]
483/// table the encoder writes.
484///
485/// Every canonical counter must be present as a JSON unsigned integer; the
486/// first one that is missing or of another type is an error naming it.
487/// Entries outside the canonical set are ignored — the encoder writes none,
488/// and a reader must not fail on a recording that carries one.
489pub fn stats_from_wire_json(stats: &Map<String, Value>) -> Result<WireStatsSnapshot, String> {
490    let mut snapshot = WireStatsSnapshot::default();
491    for counter in &STAT_COUNTERS {
492        let count = stats
493            .get(counter.key)
494            .and_then(Value::as_u64)
495            .ok_or_else(|| {
496                format!(
497                    "stats entry `{}` is missing or not an unsigned integer",
498                    counter.key
499                )
500            })?;
501        (counter.set)(&mut snapshot, count);
502    }
503    Ok(snapshot)
504}
505
506/// A mutation counter: its key in an envelope's `stats` object, its key on
507/// the Bolt wire (derived by [`StatCounter::bolt_key`]), and the
508/// [`WireStats`] accessor it encodes — with that accessor's inverse, so
509/// [`stats_to_wire_json`] and [`stats_from_wire_json`] read one table.
510#[derive(Debug, Clone, Copy)]
511pub struct StatCounter {
512    /// The counter's key in the JSON envelope's `stats` object (snake_case,
513    /// the canonical envelope vocabulary).
514    pub key: &'static str,
515    /// The [`WireStats`] accessor this counter encodes.
516    pub count: fn(&dyn WireStats) -> u64,
517    /// The inverse of `count`: writes this counter's value into a
518    /// [`WireStatsSnapshot`], so the decoder assigns the field the encoder
519    /// reads.
520    pub set: fn(&mut WireStatsSnapshot, u64),
521}
522
523impl StatCounter {
524    /// The counter's key in Bolt's `stats` map (ADR-0309): Neo4j's
525    /// kebab-case wire spelling, derived from the envelope key so no second
526    /// stored spelling can drift from it.
527    pub fn bolt_key(&self) -> Cow<'static, str> {
528        self.key.replace('_', "-").into()
529    }
530}
531
532/// The mutation counters of an envelope's `stats` object, in canonical order.
533pub const STAT_COUNTERS: [StatCounter; 11] = [
534    StatCounter {
535        key: "nodes_created",
536        count: |s| s.nodes_created(),
537        set: |s, n| s.nodes_created = n,
538    },
539    StatCounter {
540        key: "nodes_deleted",
541        count: |s| s.nodes_deleted(),
542        set: |s, n| s.nodes_deleted = n,
543    },
544    StatCounter {
545        key: "relationships_created",
546        count: |s| s.relationships_created(),
547        set: |s, n| s.relationships_created = n,
548    },
549    StatCounter {
550        key: "relationships_deleted",
551        count: |s| s.relationships_deleted(),
552        set: |s, n| s.relationships_deleted = n,
553    },
554    StatCounter {
555        key: "properties_set",
556        count: |s| s.properties_set(),
557        set: |s, n| s.properties_set = n,
558    },
559    StatCounter {
560        key: "labels_added",
561        count: |s| s.labels_added(),
562        set: |s, n| s.labels_added = n,
563    },
564    StatCounter {
565        key: "labels_removed",
566        count: |s| s.labels_removed(),
567        set: |s, n| s.labels_removed = n,
568    },
569    StatCounter {
570        key: "indexes_added",
571        count: |s| s.indexes_added(),
572        set: |s, n| s.indexes_added = n,
573    },
574    StatCounter {
575        key: "indexes_removed",
576        count: |s| s.indexes_removed(),
577        set: |s, n| s.indexes_removed = n,
578    },
579    StatCounter {
580        key: "constraints_added",
581        count: |s| s.constraints_added(),
582        set: |s, n| s.constraints_added = n,
583    },
584    StatCounter {
585        key: "constraints_removed",
586        count: |s| s.constraints_removed(),
587        set: |s, n| s.constraints_removed = n,
588    },
589];
590
591/// The ADR-0224 per-column type classification: the closed 18-kind set the
592/// engine stamps result columns with, one kind per first-row value. This
593/// enum is the single source of the canonical name spellings — both value
594/// taxonomies (the wire-side [`CypherValue`] here, the engine's core
595/// `Value` in `relate-core`'s `convert` module) classify into it, so a
596/// renamed or extended kind fails to compile at every mapping site instead
597/// of drifting into a second hand-maintained table.
598///
599/// `Uuid` and `Binary` are reserved kinds: neither value enum has a
600/// distinct variant that classifies into them today (UUID values cross as
601/// `Str`/`String` and stamp `STRING`), so the names exist only to keep a
602/// future distinct value kind from renumbering the set.
603#[derive(Debug, Clone, Copy, PartialEq, Eq)]
604pub enum ColumnTypeKind {
605    Any,
606    String,
607    Integer,
608    Float,
609    Boolean,
610    Node,
611    Relationship,
612    Path,
613    List,
614    Map,
615    Point,
616    DateTime,
617    Date,
618    Time,
619    Duration,
620    Vector,
621    Uuid,
622    Binary,
623}
624
625impl ColumnTypeKind {
626    /// The canonical ADR-0224 type-name spelling of this kind.
627    pub fn name(self) -> &'static str {
628        match self {
629            Self::Any => "ANY",
630            Self::String => "STRING",
631            Self::Integer => "INTEGER",
632            Self::Float => "FLOAT",
633            Self::Boolean => "BOOLEAN",
634            Self::Node => "NODE",
635            Self::Relationship => "RELATIONSHIP",
636            Self::Path => "PATH",
637            Self::List => "LIST",
638            Self::Map => "MAP",
639            Self::Point => "POINT",
640            Self::DateTime => "DATETIME",
641            Self::Date => "DATE",
642            Self::Time => "TIME",
643            Self::Duration => "DURATION",
644            Self::Vector => "VECTOR",
645            Self::Uuid => "UUID",
646            Self::Binary => "BINARY",
647        }
648    }
649}
650
651/// Classify a first-row value into its canonical ADR-0224 kind.
652///
653/// `Null` classifies `Any` (the stamping rule's `ANY`). `Geometry` is a
654/// distinct `CypherValue` variant but is not in the client-facing set; it
655/// reports `Point` (the same coordinate family).
656pub fn column_type_kind(value: &CypherValue) -> ColumnTypeKind {
657    match value {
658        CypherValue::Null => ColumnTypeKind::Any,
659        CypherValue::Bool(_) => ColumnTypeKind::Boolean,
660        CypherValue::Int(_) => ColumnTypeKind::Integer,
661        CypherValue::Float(_) => ColumnTypeKind::Float,
662        CypherValue::Str(_) => ColumnTypeKind::String,
663        CypherValue::List(_) => ColumnTypeKind::List,
664        CypherValue::Map(_) => ColumnTypeKind::Map,
665        CypherValue::Node { .. } => ColumnTypeKind::Node,
666        CypherValue::Relationship { .. } => ColumnTypeKind::Relationship,
667        CypherValue::Path { .. } => ColumnTypeKind::Path,
668        CypherValue::Date(_) => ColumnTypeKind::Date,
669        CypherValue::Time(_, _) => ColumnTypeKind::Time,
670        CypherValue::DateTime(_, _) => ColumnTypeKind::DateTime,
671        CypherValue::LocalDateTime(_) => ColumnTypeKind::DateTime,
672        CypherValue::Duration(_) => ColumnTypeKind::Duration,
673        CypherValue::Point(_) => ColumnTypeKind::Point,
674        // Distinct value kind, same coordinate family — see the enum docs.
675        CypherValue::Geometry(_) => ColumnTypeKind::Point,
676        CypherValue::Vector { .. } => ColumnTypeKind::Vector,
677    }
678}
679
680/// One canonical ADR-0224 per-column type name for a first-row value — the
681/// name spelling of [`column_type_kind`], for callers that want the string
682/// directly. The engine stamps each result column with one of the 18
683/// canonical names at result construction, from the first row only —
684/// Cypher columns are heterogeneous, and the name makes no claim about
685/// later rows. This mapping is the wire-side spelling of the engine's
686/// `QueryResult::column_types` stamp.
687pub fn column_type_name(value: &CypherValue) -> &'static str {
688    column_type_kind(value).name()
689}
690
691/// Shared golden fixtures: the cross-surface anti-drift substrate.
692///
693/// Every Relate surface (C FFI, CLI, and — transitively — the language
694/// bindings) is expected to serialize through
695/// [`value_to_wire_json`]. These fixtures pin the exact expected JSON for every
696/// variant so that any surface diverging from the canonical encoding fails a
697/// test. The module is public and always compiled so the CLI, FFI (and
698/// any other) test suites can `use relate_model::wire::golden;` and run
699/// [`golden::assert_all_match`] against their own serializer.
700pub mod golden;
701
702#[cfg(test)]
703mod tests;
704
705// The one hand-built plan wire fixture — its own file so the wire
706// accessor's and the agent document's test modules share one builder,
707// never a second copy of the metric-args block.
708#[cfg(test)]
709#[path = "plan_test_fixtures.rs"]
710pub(crate) mod plan_test_fixtures;
711
712// ---------------------------------------------------------------------------
713// Structured query plan wire form (ADR-0344/0345) — the node types and
714// decoder live in `plan_wire`, the key vocabulary in its own `plan_keys`
715// module; both are re-exported here so the one public path stays under
716// `wire`.
717// ---------------------------------------------------------------------------
718
719// The plan args' scalar readers (the optional extraction policies and
720// the all-or-none group read) — their own module below the node accessor
721// and the fused-child parser, so both read it and neither reads the
722// other.
723
724#[path = "plan_args.rs"]
725mod plan_args;
726
727#[path = "plan_wire.rs"]
728mod plan_wire;
729
730// The PROFILE metric-wire family (ADR-0344 phase 2 + metric fields): the
731// metric set and every shape it composes — its own module beside the node
732// wire form that reads it, mirroring the fused-child and memo shapes'
733// placement; `wire::PlanMetricsWire` stays the one public path.
734
735#[path = "plan_metrics_wire.rs"]
736mod plan_metrics_wire;
737
738// The fused virtual child's wire shape (virtual plan operators) — its
739// own module beside the node accessor that reads it, mirroring the key
740// vocabulary's placement.
741
742#[path = "plan_fused.rs"]
743mod plan_fused;
744
745#[path = "plan_memo.rs"]
746mod plan_memo;
747
748// The plan wire form's key vocabulary, its own module beside the types and
749// decoder it names (`plan_keys.rs`); `wire::plan_keys` stays the one public
750// path.
751#[path = "plan_keys.rs"]
752pub mod plan_keys;
753
754pub use plan_fused::{FusedChildWire, PlanFusedMetricsWire};
755pub use plan_memo::{MemoKindWire, MemoKindsWire, PlanMemoWire};
756pub use plan_metrics_wire::{
757    EstimateProvenance, KernelRungWire, PlanExpandIntoWire, PlanHashJoinWire, PlanInTxWire,
758    PlanMetricsWire, PlanPhasesWire, PlanProfiledFacts, PlanReadsWire, PlanVectorScanWire,
759};
760pub use plan_wire::{
761    metric_i64, metric_u64, plan_node_wire, plan_subtree_totals, profiled_facts, time_ns_ms,
762    PlanNodeWire, CYPHER_VERSION, NEO4J_PLANNER_IMPL, PLAN_UNAVAILABLE,
763};
764
765// The typed plan-warning vocabulary (LABS-461: one warning type) — its
766// own module beside the plan wire form it parses into, mirroring the
767// notification vocabulary's placement; re-exported here so
768// `wire::PlanWarning` is the one public path.
769
770#[path = "plan_warning.rs"]
771mod plan_warning;
772
773pub use plan_warning::{estimation_miss, ratio_defined, warning_wire_json, PlanWarning};
774
775// The agent-native plan projection (`relate.plan/v1`, LABS-370) — our
776// own API dialect beside the Neo4j-facing one, reading the same typed view.
777
778#[path = "agent_plan.rs"]
779mod agent_plan;
780
781pub use agent_plan::{plan_document, SCHEMA as PLAN_SCHEMA};
782
783// ---------------------------------------------------------------------------
784// Query notifications (ADR-0363) — lives in `notification_wire`, re-exported
785// here so `wire::Notification` is the one public path (the plan vocabulary's
786// layout).
787// ---------------------------------------------------------------------------
788
789#[path = "notification_wire.rs"]
790mod notification_wire;
791
792pub use notification_wire::{
793    notification_keys, notification_to_neo4j_entries, notification_to_neo4j_json,
794    notification_to_wire_json, notifications_to_wire_json, Notification, NotificationCategory,
795    NotificationKind, NotificationSeverity,
796};
797
798// ---------------------------------------------------------------------------
799// The response-envelope family (the canonical success envelope with the
800// ADR-0491 phase split, the error envelope, the bundled timing stamp) —
801// lives in `wire/envelope`, re-exported here so `wire::response_envelope`
802// is the one public path.
803// ---------------------------------------------------------------------------
804
805mod envelope;
806
807pub use envelope::{error_envelope, response_envelope, TimingStampMs};