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