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};
145
146/// The `kind` discriminator of a wire node object (ADR-0223). Decoder sides
147/// match on these constants instead of re-typing the literals.
148pub const WIRE_KIND_NODE: &str = "node";
149
150/// The `kind` discriminator of a wire relationship object (ADR-0223).
151pub const WIRE_KIND_RELATIONSHIP: &str = "relationship";
152
153/// Encode a [`CypherValue`] as its canonical wire JSON.
154///
155/// Covers all 18 variants with structured, self-describing encodings; no
156/// variant falls through to a `Display` string except the five temporal
157/// variants, whose ISO-8601 string *is* the canonical encoding. See the module
158/// docs for the full table.
159pub fn value_to_wire_json(val: &CypherValue) -> Value {
160    match val {
161        CypherValue::Null => Value::Null,
162        CypherValue::Bool(b) => Value::Bool(*b),
163        CypherValue::Int(i) => Value::Number((*i).into()),
164        CypherValue::Float(f) => json_f64(*f),
165        CypherValue::Str(s) => Value::String(s.clone()),
166        CypherValue::List(items) => Value::Array(items.iter().map(value_to_wire_json).collect()),
167        CypherValue::Map(map) => Value::Object(map_to_wire_json(map)),
168        CypherValue::Node {
169            id,
170            labels,
171            properties,
172        } => {
173            let mut obj = Map::new();
174            // ADR-0223: the `kind` discriminator lets clients dispatch on a
175            // documented field instead of shape-sniffing.
176            obj.insert("kind".into(), Value::String(WIRE_KIND_NODE.into()));
177            obj.insert("id".into(), Value::Number((*id).into()));
178            obj.insert(
179                "labels".into(),
180                Value::Array(labels.iter().map(|l| Value::String(l.clone())).collect()),
181            );
182            obj.insert(
183                "properties".into(),
184                Value::Object(map_to_wire_json(properties)),
185            );
186            Value::Object(obj)
187        }
188        CypherValue::Relationship {
189            id,
190            start_id,
191            end_id,
192            rel_type,
193            properties,
194        } => {
195            let mut obj = Map::new();
196            // ADR-0223: see the `Node` arm.
197            obj.insert("kind".into(), Value::String(WIRE_KIND_RELATIONSHIP.into()));
198            obj.insert("id".into(), Value::Number((*id).into()));
199            obj.insert("type".into(), Value::String(rel_type.clone()));
200            obj.insert("start_node".into(), Value::Number((*start_id).into()));
201            obj.insert("end_node".into(), Value::Number((*end_id).into()));
202            obj.insert(
203                "properties".into(),
204                Value::Object(map_to_wire_json(properties)),
205            );
206            Value::Object(obj)
207        }
208        CypherValue::Path {
209            nodes,
210            relationships,
211        } => {
212            // Alternating [node, rel, node, rel, …, node]. A well-formed path
213            // has `nodes.len() == relationships.len() + 1`, so the trailing
214            // node emits no following relationship.
215            let mut items = Vec::with_capacity(nodes.len() + relationships.len());
216            for (i, n) in nodes.iter().enumerate() {
217                items.push(value_to_wire_json(n));
218                if let Some(r) = relationships.get(i) {
219                    items.push(value_to_wire_json(r));
220                }
221            }
222            Value::Array(items)
223        }
224        // Temporal values: canonical ISO-8601 Display strings (documented,
225        // stable, and tag-free). This is the one intentional "Display" arm.
226        CypherValue::Date(_)
227        | CypherValue::Time(_, _)
228        | CypherValue::DateTime(_, _)
229        | CypherValue::LocalDateTime(_)
230        | CypherValue::Duration(_) => Value::String(val.to_string()),
231        CypherValue::Point(p) => point_to_wire_json(p),
232        CypherValue::Geometry(g) => geometry_to_wire_json(g),
233        CypherValue::Vector { coord, dim, values } => {
234            let mut obj = Map::new();
235            obj.insert(
236                "type".into(),
237                Value::String(coord.canonical_name().to_string()),
238            );
239            obj.insert("dim".into(), Value::Number((*dim as u64).into()));
240            obj.insert(
241                "values".into(),
242                Value::Array(values.iter().map(value_to_wire_json).collect()),
243            );
244            Value::Object(obj)
245        }
246    }
247}
248
249/// Encode a property/value map (used for node & relationship `properties` and
250/// for `CypherValue::Map`).
251fn map_to_wire_json(map: &IndexMap<String, CypherValue>) -> Map<String, Value> {
252    map.iter()
253        .map(|(k, v)| (k.clone(), value_to_wire_json(v)))
254        .collect()
255}
256
257/// Encode an `f64` as wire JSON: a JSON number when finite, otherwise the
258/// JSON string of its `CypherValue` `Display` spelling (`"NaN"`/`"Inf"`/
259/// `"-Inf"`, ADR-0280).
260pub fn json_f64(f: f64) -> Value {
261    serde_json::Number::from_f64(f)
262        .map(Value::Number)
263        .unwrap_or_else(|| Value::String(CypherValue::Float(f).to_string()))
264}
265
266/// The Neo4j CRS name for an SRID (used as the `crs` point marker) — the
267/// canonical mapping every surface shares (ADR-0280 wire shape).
268pub fn crs_name(srid: i32) -> &'static str {
269    match srid {
270        4326 => "wgs-84",
271        4979 => "wgs-84-3d",
272        7203 => "cartesian",
273        9157 => "cartesian-3d",
274        _ => "cartesian",
275    }
276}
277
278fn point_to_wire_json(p: &PointValue) -> Value {
279    let mut obj = Map::new();
280    obj.insert("srid".into(), Value::Number(p.srid.into()));
281    obj.insert("crs".into(), Value::String(crs_name(p.srid).to_string()));
282    // Geographic and cartesian differ only in the coordinate key names,
283    // which are the shared axis vocabulary's two spellings.
284    let [x_key, y_key, z_key] = point_axis_keys(is_geographic(p.srid));
285    obj.insert(x_key.into(), json_f64(p.x));
286    obj.insert(y_key.into(), json_f64(p.y));
287    if let Some(z) = p.z {
288        obj.insert(z_key.into(), json_f64(z));
289    }
290    Value::Object(obj)
291}
292
293fn coords_to_wire_json(coords: &[[f64; 2]]) -> Value {
294    Value::Array(
295        coords
296            .iter()
297            .map(|c| Value::Array(vec![json_f64(c[0]), json_f64(c[1])]))
298            .collect(),
299    )
300}
301
302fn geometry_to_wire_json(g: &GeometryValue) -> Value {
303    let mut obj = Map::new();
304    obj.insert("type".into(), Value::String(g.type_name().to_string()));
305    match g {
306        GeometryValue::LineString { coordinates, .. } => {
307            obj.insert("coordinates".into(), coords_to_wire_json(coordinates));
308        }
309        GeometryValue::Polygon { rings, .. } => {
310            obj.insert(
311                "coordinates".into(),
312                Value::Array(rings.iter().map(|r| coords_to_wire_json(r)).collect()),
313            );
314        }
315        GeometryValue::MultiPoint { points, .. } => {
316            obj.insert("coordinates".into(), coords_to_wire_json(points));
317        }
318        GeometryValue::MultiLineString { lines, .. } => {
319            obj.insert(
320                "coordinates".into(),
321                Value::Array(lines.iter().map(|l| coords_to_wire_json(l)).collect()),
322            );
323        }
324        GeometryValue::MultiPolygon { polygons, .. } => {
325            obj.insert(
326                "coordinates".into(),
327                Value::Array(
328                    polygons
329                        .iter()
330                        .map(|poly| {
331                            Value::Array(poly.iter().map(|r| coords_to_wire_json(r)).collect())
332                        })
333                        .collect(),
334                ),
335            );
336        }
337        GeometryValue::GeometryCollection { geometries, .. } => {
338            obj.insert(
339                "geometries".into(),
340                Value::Array(geometries.iter().map(geometry_to_wire_json).collect()),
341            );
342        }
343    }
344    Value::Object(obj)
345}
346
347/// Encode one result row (an ordered column→value map) as a JSON object.
348///
349/// Columns are taken from `columns` (preserving the query's column order in the
350/// underlying ordered map); a column absent from `row` encodes as `null`.
351pub fn row_to_wire_json(columns: &[String], row: &IndexMap<String, CypherValue>) -> Value {
352    let mut obj = Map::new();
353    for col in columns {
354        let v = row.get(col).map(value_to_wire_json).unwrap_or(Value::Null);
355        obj.insert(col.clone(), v);
356    }
357    Value::Object(obj)
358}
359
360/// Build the canonical wire `rows` array for a query result.
361///
362/// This is the single, shared assembly point for the row container so the
363/// JSON surfaces (C FFI, CLI) cannot diverge on it. It applies
364/// the **write-only rule**: a statement that produces no result columns (a
365/// `CREATE`/`MERGE`/`SET`/… without `RETURN`) yields an empty `rows` array — not
366/// a `[{}]` array of empty objects — even though the engine emits one driving
367/// row per input row (seeded with a single empty row for a top-level write).
368/// When there are columns, each row is encoded via [`row_to_wire_json`].
369///
370/// Historically only the JSONL server guarded the empty-columns case; the FFI
371/// and WASM surfaces mapped every driving row unconditionally and so emitted
372/// `[{}]` for a write-only statement. Routing all three through this helper
373/// makes that drift structurally impossible (pinned by
374/// [`golden::envelope_write_only`]).
375pub fn rows_for_result(columns: &[String], rows: &[IndexMap<String, CypherValue>]) -> Vec<Value> {
376    if columns.is_empty() {
377        Vec::new()
378    } else {
379        rows.iter()
380            .map(|row| row_to_wire_json(columns, row))
381            .collect()
382    }
383}
384
385/// The 11 canonical mutation counters, read as `u64`.
386///
387/// Implemented by [`WireStatsSnapshot`] here (built from the executor's
388/// `QueryStats` via `relate::query_stats_to_wire`), so
389/// `stats_to_wire_json` can serialize either without `relate-model`
390/// depending on the executor.
391pub trait WireStats {
392    fn nodes_created(&self) -> u64;
393    fn nodes_deleted(&self) -> u64;
394    fn relationships_created(&self) -> u64;
395    fn relationships_deleted(&self) -> u64;
396    fn properties_set(&self) -> u64;
397    fn labels_added(&self) -> u64;
398    fn labels_removed(&self) -> u64;
399    fn indexes_added(&self) -> u64;
400    fn indexes_removed(&self) -> u64;
401    fn constraints_added(&self) -> u64;
402    fn constraints_removed(&self) -> u64;
403}
404
405/// A plain, model-owned carrier of the 11 counters — a [`WireStats`] value that
406/// does not require the engine crate (used by the golden fixtures and by any
407/// surface that already has counts in hand).
408#[derive(Debug, Clone, Default, PartialEq, Eq)]
409pub struct WireStatsSnapshot {
410    pub nodes_created: u64,
411    pub nodes_deleted: u64,
412    pub relationships_created: u64,
413    pub relationships_deleted: u64,
414    pub properties_set: u64,
415    pub labels_added: u64,
416    pub labels_removed: u64,
417    pub indexes_added: u64,
418    pub indexes_removed: u64,
419    pub constraints_added: u64,
420    pub constraints_removed: u64,
421}
422
423impl WireStats for WireStatsSnapshot {
424    fn nodes_created(&self) -> u64 {
425        self.nodes_created
426    }
427    fn nodes_deleted(&self) -> u64 {
428        self.nodes_deleted
429    }
430    fn relationships_created(&self) -> u64 {
431        self.relationships_created
432    }
433    fn relationships_deleted(&self) -> u64 {
434        self.relationships_deleted
435    }
436    fn properties_set(&self) -> u64 {
437        self.properties_set
438    }
439    fn labels_added(&self) -> u64 {
440        self.labels_added
441    }
442    fn labels_removed(&self) -> u64 {
443        self.labels_removed
444    }
445    fn indexes_added(&self) -> u64 {
446        self.indexes_added
447    }
448    fn indexes_removed(&self) -> u64 {
449        self.indexes_removed
450    }
451    fn constraints_added(&self) -> u64 {
452        self.constraints_added
453    }
454    fn constraints_removed(&self) -> u64 {
455        self.constraints_removed
456    }
457}
458
459/// Encode the 11 canonical mutation counters as a JSON object: snake_case keys,
460/// zeros included. See the module docs for the canonical name set.
461pub fn stats_to_wire_json(stats: &dyn WireStats) -> Value {
462    Value::Object(
463        STAT_COUNTERS
464            .iter()
465            .map(|counter| (counter.key.to_string(), (counter.count)(stats).into()))
466            .collect(),
467    )
468}
469
470/// Decode an envelope's `stats` object into the 11 canonical counters — the
471/// inverse of [`stats_to_wire_json`], reading the same [`STAT_COUNTERS`]
472/// table the encoder writes.
473///
474/// Every canonical counter must be present as a JSON unsigned integer; the
475/// first one that is missing or of another type is an error naming it.
476/// Entries outside the canonical set are ignored — the encoder writes none,
477/// and a reader must not fail on a recording that carries one.
478pub fn stats_from_wire_json(stats: &Map<String, Value>) -> Result<WireStatsSnapshot, String> {
479    let mut snapshot = WireStatsSnapshot::default();
480    for counter in &STAT_COUNTERS {
481        let count = stats
482            .get(counter.key)
483            .and_then(Value::as_u64)
484            .ok_or_else(|| {
485                format!(
486                    "stats entry `{}` is missing or not an unsigned integer",
487                    counter.key
488                )
489            })?;
490        (counter.set)(&mut snapshot, count);
491    }
492    Ok(snapshot)
493}
494
495/// A mutation counter: its key in an envelope's `stats` object, its key on
496/// the Bolt wire (derived by [`StatCounter::bolt_key`]), and the
497/// [`WireStats`] accessor it encodes — with that accessor's inverse, so
498/// [`stats_to_wire_json`] and [`stats_from_wire_json`] read one table.
499#[derive(Debug, Clone, Copy)]
500pub struct StatCounter {
501    /// The counter's key in the JSON envelope's `stats` object (snake_case,
502    /// the canonical envelope vocabulary).
503    pub key: &'static str,
504    /// The [`WireStats`] accessor this counter encodes.
505    pub count: fn(&dyn WireStats) -> u64,
506    /// The inverse of `count`: writes this counter's value into a
507    /// [`WireStatsSnapshot`], so the decoder assigns the field the encoder
508    /// reads.
509    pub set: fn(&mut WireStatsSnapshot, u64),
510}
511
512impl StatCounter {
513    /// The counter's key in Bolt's `stats` map (ADR-0309): Neo4j's
514    /// kebab-case wire spelling, derived from the envelope key so no second
515    /// stored spelling can drift from it.
516    pub fn bolt_key(&self) -> Cow<'static, str> {
517        self.key.replace('_', "-").into()
518    }
519}
520
521/// The mutation counters of an envelope's `stats` object, in canonical order.
522pub const STAT_COUNTERS: [StatCounter; 11] = [
523    StatCounter {
524        key: "nodes_created",
525        count: |s| s.nodes_created(),
526        set: |s, n| s.nodes_created = n,
527    },
528    StatCounter {
529        key: "nodes_deleted",
530        count: |s| s.nodes_deleted(),
531        set: |s, n| s.nodes_deleted = n,
532    },
533    StatCounter {
534        key: "relationships_created",
535        count: |s| s.relationships_created(),
536        set: |s, n| s.relationships_created = n,
537    },
538    StatCounter {
539        key: "relationships_deleted",
540        count: |s| s.relationships_deleted(),
541        set: |s, n| s.relationships_deleted = n,
542    },
543    StatCounter {
544        key: "properties_set",
545        count: |s| s.properties_set(),
546        set: |s, n| s.properties_set = n,
547    },
548    StatCounter {
549        key: "labels_added",
550        count: |s| s.labels_added(),
551        set: |s, n| s.labels_added = n,
552    },
553    StatCounter {
554        key: "labels_removed",
555        count: |s| s.labels_removed(),
556        set: |s, n| s.labels_removed = n,
557    },
558    StatCounter {
559        key: "indexes_added",
560        count: |s| s.indexes_added(),
561        set: |s, n| s.indexes_added = n,
562    },
563    StatCounter {
564        key: "indexes_removed",
565        count: |s| s.indexes_removed(),
566        set: |s, n| s.indexes_removed = n,
567    },
568    StatCounter {
569        key: "constraints_added",
570        count: |s| s.constraints_added(),
571        set: |s, n| s.constraints_added = n,
572    },
573    StatCounter {
574        key: "constraints_removed",
575        count: |s| s.constraints_removed(),
576        set: |s, n| s.constraints_removed = n,
577    },
578];
579
580/// The ADR-0224 per-column type classification: the closed 18-kind set the
581/// engine stamps result columns with, one kind per first-row value. This
582/// enum is the single source of the canonical name spellings — both value
583/// taxonomies (the wire-side [`CypherValue`] here, the engine's core
584/// `Value` in `relate-core`'s `convert` module) classify into it, so a
585/// renamed or extended kind fails to compile at every mapping site instead
586/// of drifting into a second hand-maintained table.
587///
588/// `Uuid` and `Binary` are reserved kinds: neither value enum has a
589/// distinct variant that classifies into them today (UUID values cross as
590/// `Str`/`String` and stamp `STRING`), so the names exist only to keep a
591/// future distinct value kind from renumbering the set.
592#[derive(Debug, Clone, Copy, PartialEq, Eq)]
593pub enum ColumnTypeKind {
594    Any,
595    String,
596    Integer,
597    Float,
598    Boolean,
599    Node,
600    Relationship,
601    Path,
602    List,
603    Map,
604    Point,
605    DateTime,
606    Date,
607    Time,
608    Duration,
609    Vector,
610    Uuid,
611    Binary,
612}
613
614impl ColumnTypeKind {
615    /// The canonical ADR-0224 type-name spelling of this kind.
616    pub fn name(self) -> &'static str {
617        match self {
618            Self::Any => "ANY",
619            Self::String => "STRING",
620            Self::Integer => "INTEGER",
621            Self::Float => "FLOAT",
622            Self::Boolean => "BOOLEAN",
623            Self::Node => "NODE",
624            Self::Relationship => "RELATIONSHIP",
625            Self::Path => "PATH",
626            Self::List => "LIST",
627            Self::Map => "MAP",
628            Self::Point => "POINT",
629            Self::DateTime => "DATETIME",
630            Self::Date => "DATE",
631            Self::Time => "TIME",
632            Self::Duration => "DURATION",
633            Self::Vector => "VECTOR",
634            Self::Uuid => "UUID",
635            Self::Binary => "BINARY",
636        }
637    }
638}
639
640/// Classify a first-row value into its canonical ADR-0224 kind.
641///
642/// `Null` classifies `Any` (the stamping rule's `ANY`). `Geometry` is a
643/// distinct `CypherValue` variant but is not in the client-facing set; it
644/// reports `Point` (the same coordinate family).
645pub fn column_type_kind(value: &CypherValue) -> ColumnTypeKind {
646    match value {
647        CypherValue::Null => ColumnTypeKind::Any,
648        CypherValue::Bool(_) => ColumnTypeKind::Boolean,
649        CypherValue::Int(_) => ColumnTypeKind::Integer,
650        CypherValue::Float(_) => ColumnTypeKind::Float,
651        CypherValue::Str(_) => ColumnTypeKind::String,
652        CypherValue::List(_) => ColumnTypeKind::List,
653        CypherValue::Map(_) => ColumnTypeKind::Map,
654        CypherValue::Node { .. } => ColumnTypeKind::Node,
655        CypherValue::Relationship { .. } => ColumnTypeKind::Relationship,
656        CypherValue::Path { .. } => ColumnTypeKind::Path,
657        CypherValue::Date(_) => ColumnTypeKind::Date,
658        CypherValue::Time(_, _) => ColumnTypeKind::Time,
659        CypherValue::DateTime(_, _) => ColumnTypeKind::DateTime,
660        CypherValue::LocalDateTime(_) => ColumnTypeKind::DateTime,
661        CypherValue::Duration(_) => ColumnTypeKind::Duration,
662        CypherValue::Point(_) => ColumnTypeKind::Point,
663        // Distinct value kind, same coordinate family — see the enum docs.
664        CypherValue::Geometry(_) => ColumnTypeKind::Point,
665        CypherValue::Vector { .. } => ColumnTypeKind::Vector,
666    }
667}
668
669/// One canonical ADR-0224 per-column type name for a first-row value — the
670/// name spelling of [`column_type_kind`], for callers that want the string
671/// directly. The engine stamps each result column with one of the 18
672/// canonical names at result construction, from the first row only —
673/// Cypher columns are heterogeneous, and the name makes no claim about
674/// later rows. This mapping is the wire-side spelling of the engine's
675/// `QueryResult::column_types` stamp.
676pub fn column_type_name(value: &CypherValue) -> &'static str {
677    column_type_kind(value).name()
678}
679
680/// Shared golden fixtures: the cross-surface anti-drift substrate.
681///
682/// Every Relate surface (C FFI, CLI, and — transitively — the language
683/// bindings) is expected to serialize through
684/// [`value_to_wire_json`]. These fixtures pin the exact expected JSON for every
685/// variant so that any surface diverging from the canonical encoding fails a
686/// test. The module is public and always compiled so the CLI, FFI (and
687/// any other) test suites can `use relate_model::wire::golden;` and run
688/// [`golden::assert_all_match`] against their own serializer.
689pub mod golden;
690
691#[cfg(test)]
692mod tests;
693
694// The one hand-built plan wire fixture — its own file so the wire
695// accessor's and the agent document's test modules share one builder,
696// never a second copy of the metric-args block.
697#[cfg(test)]
698#[path = "plan_test_fixtures.rs"]
699pub(crate) mod plan_test_fixtures;
700
701// ---------------------------------------------------------------------------
702// Structured query plan wire form (ADR-0344/0345) — the node types and
703// decoder live in `plan_wire`, the key vocabulary in its own `plan_keys`
704// module; both are re-exported here so the one public path stays under
705// `wire`.
706// ---------------------------------------------------------------------------
707
708// The plan args' scalar readers (the optional extraction policies and
709// the all-or-none group read) — their own module below the node accessor
710// and the fused-child parser, so both read it and neither reads the
711// other.
712
713#[path = "plan_args.rs"]
714mod plan_args;
715
716#[path = "plan_wire.rs"]
717mod plan_wire;
718
719// The PROFILE metric-wire family (ADR-0344 phase 2 + metric fields): the
720// metric set and every shape it composes — its own module beside the node
721// wire form that reads it, mirroring the fused-child and memo shapes'
722// placement; `wire::PlanMetricsWire` stays the one public path.
723
724#[path = "plan_metrics_wire.rs"]
725mod plan_metrics_wire;
726
727// The fused virtual child's wire shape (virtual plan operators) — its
728// own module beside the node accessor that reads it, mirroring the key
729// vocabulary's placement.
730
731#[path = "plan_fused.rs"]
732mod plan_fused;
733
734#[path = "plan_memo.rs"]
735mod plan_memo;
736
737// The plan wire form's key vocabulary, its own module beside the types and
738// decoder it names (`plan_keys.rs`); `wire::plan_keys` stays the one public
739// path.
740#[path = "plan_keys.rs"]
741pub mod plan_keys;
742
743pub use plan_fused::{FusedChildWire, PlanFusedMetricsWire};
744pub use plan_memo::{MemoKindWire, MemoKindsWire, PlanMemoWire};
745pub use plan_metrics_wire::{
746    KernelRungWire, PlanInTxWire, PlanMetricsWire, PlanPhasesWire, PlanProfiledFacts, PlanReadsWire,
747};
748pub use plan_wire::{
749    metric_i64, metric_u64, plan_node_wire, plan_subtree_totals, profiled_facts, time_ns_ms,
750    PlanNodeWire, CYPHER_VERSION, NEO4J_PLANNER_IMPL, PLAN_UNAVAILABLE,
751};
752
753// The typed plan-warning vocabulary (LABS-461: one warning type) — its
754// own module beside the plan wire form it parses into, mirroring the
755// notification vocabulary's placement; re-exported here so
756// `wire::PlanWarning` is the one public path.
757
758#[path = "plan_warning.rs"]
759mod plan_warning;
760
761pub use plan_warning::{estimation_miss, ratio_defined, warning_wire_json, PlanWarning};
762
763// The agent-native plan projection (`relate.plan/v1`, LABS-370) — our
764// own API dialect beside the Neo4j-facing one, reading the same typed view.
765
766#[path = "agent_plan.rs"]
767mod agent_plan;
768
769pub use agent_plan::{plan_document, SCHEMA as PLAN_SCHEMA};
770
771// ---------------------------------------------------------------------------
772// Query notifications (ADR-0363) — lives in `notification_wire`, re-exported
773// here so `wire::Notification` is the one public path (the plan vocabulary's
774// layout).
775// ---------------------------------------------------------------------------
776
777#[path = "notification_wire.rs"]
778mod notification_wire;
779
780pub use notification_wire::{
781    notification_keys, notification_to_neo4j_entries, notification_to_neo4j_json,
782    notification_to_wire_json, notifications_to_wire_json, Notification, NotificationCategory,
783    NotificationKind, NotificationSeverity,
784};
785
786// ---------------------------------------------------------------------------
787// The response-envelope family (the canonical success envelope with the
788// ADR-0491 phase split, the error envelope, the bundled timing stamp) —
789// lives in `wire/envelope`, re-exported here so `wire::response_envelope`
790// is the one public path.
791// ---------------------------------------------------------------------------
792
793mod envelope;
794
795pub use envelope::{error_envelope, response_envelope, TimingStampMs};