Skip to main content

relate_model/wire/
golden.rs

1use super::*;
2use crate::value::{GeometryValue, IsoDuration, PointValue, VectorCoordKind};
3use chrono::{FixedOffset, NaiveDate, NaiveTime, TimeZone};
4
5/// The fixed `elapsed_ms` the envelope fixtures pin (ADR-0221): real
6/// surfaces pass the engine-reported value; fixtures use a fixed value so
7/// the expected envelope is deterministic. `0.5` so the phase fixtures can
8/// partition it exactly (see [`FIXTURE_TIMING_STAMP`]) — binary fractions,
9/// no f64 rounding in the fixture's own arithmetic.
10pub const FIXTURE_ELAPSED_MS: f64 = 0.5;
11
12/// The fixed timing stamp the ADR-0491 envelope fixtures pin: real
13/// surfaces pass the engine-reported timings; fixtures use fixed values so
14/// the expected envelope is deterministic. The total is the shared
15/// [`FIXTURE_ELAPSED_MS`] (re-sourced, never re-typed); the phases are
16/// binary fractions that sum to exactly it — the fixture's own example of
17/// the ADR-0491 rule that the split partitions the total's window — and
18/// the LABS-1120 fine sub-windows partition their phases the same way
19/// (`lex_parse` + `rewrite` + `lower` = `parse`;
20/// `result_generation` < `execute`).
21pub const FIXTURE_TIMING_STAMP: TimingStampMs = TimingStampMs {
22    elapsed_ms: FIXTURE_ELAPSED_MS,
23    parse_ms: 0.25,
24    plan_ms: 0.1875,
25    execute_ms: 0.0625,
26    lex_parse_ms: 0.125,
27    rewrite_ms: 0.0625,
28    lower_ms: 0.0625,
29    result_generation_ms: 0.03125,
30    plan_cache: "miss",
31};
32
33/// A single named value fixture: a `CypherValue` and its expected canonical
34/// wire JSON.
35pub struct ValueFixture {
36    pub name: &'static str,
37    pub value: CypherValue,
38    pub expected: Value,
39}
40
41fn node_alice() -> CypherValue {
42    let mut props = IndexMap::new();
43    props.insert("name".to_string(), CypherValue::Str("Alice".into()));
44    props.insert("age".to_string(), CypherValue::Int(30));
45    CypherValue::Node {
46        id: 7,
47        labels: vec!["Person".into(), "User".into()],
48        properties: props,
49    }
50}
51
52fn node_bob() -> CypherValue {
53    let mut props = IndexMap::new();
54    props.insert("name".to_string(), CypherValue::Str("Bob".into()));
55    CypherValue::Node {
56        id: 8,
57        labels: vec!["Person".into()],
58        properties: props,
59    }
60}
61
62fn rel_knows() -> CypherValue {
63    let mut props = IndexMap::new();
64    props.insert("since".to_string(), CypherValue::Int(2020));
65    CypherValue::Relationship {
66        id: 11,
67        start_id: 7,
68        end_id: 8,
69        rel_type: "KNOWS".into(),
70        properties: props,
71    }
72}
73
74/// Every variant (plus a heterogeneous list) paired with its expected wire
75/// JSON. The expected values are hand-authored (not derived from
76/// [`value_to_wire_json`]) so they genuinely pin the contract.
77pub fn value_fixtures() -> Vec<ValueFixture> {
78    let offset = FixedOffset::east_opt(2 * 3600).unwrap();
79    let ndt = NaiveDate::from_ymd_opt(2024, 3, 14)
80        .unwrap()
81        .and_hms_opt(12, 30, 45)
82        .unwrap();
83    let zoned = offset.from_local_datetime(&ndt).unwrap();
84
85    vec![
86        ValueFixture {
87            name: "null",
88            value: CypherValue::Null,
89            expected: Value::Null,
90        },
91        ValueFixture {
92            name: "bool",
93            value: CypherValue::Bool(true),
94            expected: serde_json::json!(true),
95        },
96        ValueFixture {
97            name: "int",
98            value: CypherValue::Int(42),
99            expected: serde_json::json!(42),
100        },
101        ValueFixture {
102            name: "float",
103            value: CypherValue::Float(3.5),
104            expected: serde_json::json!(3.5),
105        },
106        // ADR-0280: non-finite floats encode as their `Display` spellings,
107        // never `null`.
108        ValueFixture {
109            name: "float_nan",
110            value: CypherValue::Float(f64::NAN),
111            expected: serde_json::json!("NaN"),
112        },
113        ValueFixture {
114            name: "float_positive_infinity",
115            value: CypherValue::Float(f64::INFINITY),
116            expected: serde_json::json!("Inf"),
117        },
118        ValueFixture {
119            name: "float_negative_infinity",
120            value: CypherValue::Float(f64::NEG_INFINITY),
121            expected: serde_json::json!("-Inf"),
122        },
123        ValueFixture {
124            name: "string",
125            value: CypherValue::Str("hello".into()),
126            expected: serde_json::json!("hello"),
127        },
128        ValueFixture {
129            name: "list_heterogeneous",
130            value: CypherValue::List(vec![
131                CypherValue::Int(1),
132                CypherValue::Str("two".into()),
133                CypherValue::Bool(true),
134                CypherValue::Null,
135            ]),
136            expected: serde_json::json!([1, "two", true, null]),
137        },
138        ValueFixture {
139            name: "map",
140            value: {
141                let mut m = IndexMap::new();
142                m.insert("a".to_string(), CypherValue::Int(1));
143                m.insert("b".to_string(), CypherValue::Str("x".into()));
144                CypherValue::Map(m)
145            },
146            expected: serde_json::json!({"a": 1, "b": "x"}),
147        },
148        ValueFixture {
149            name: "node",
150            value: node_alice(),
151            expected: serde_json::json!({
152                "kind": "node",
153                "id": 7,
154                "labels": ["Person", "User"],
155                "properties": {"name": "Alice", "age": 30}
156            }),
157        },
158        ValueFixture {
159            name: "relationship",
160            value: rel_knows(),
161            expected: serde_json::json!({
162                "kind": "relationship",
163                "id": 11,
164                "type": "KNOWS",
165                "start_node": 7,
166                "end_node": 8,
167                "properties": {"since": 2020}
168            }),
169        },
170        ValueFixture {
171            name: "path",
172            value: CypherValue::Path {
173                nodes: vec![node_alice(), node_bob()],
174                relationships: vec![rel_knows()],
175            },
176            expected: serde_json::json!([
177                {
178                    "kind": "node",
179                    "id": 7,
180                    "labels": ["Person", "User"],
181                    "properties": {"name": "Alice", "age": 30}
182                },
183                {
184                    "kind": "relationship",
185                    "id": 11,
186                    "type": "KNOWS",
187                    "start_node": 7,
188                    "end_node": 8,
189                    "properties": {"since": 2020}
190                },
191                {
192                    "kind": "node",
193                    "id": 8,
194                    "labels": ["Person"],
195                    "properties": {"name": "Bob"}
196                }
197            ]),
198        },
199        ValueFixture {
200            name: "date",
201            value: CypherValue::Date(NaiveDate::from_ymd_opt(2024, 3, 14).unwrap()),
202            expected: serde_json::json!("2024-03-14"),
203        },
204        ValueFixture {
205            name: "time",
206            value: CypherValue::Time(NaiveTime::from_hms_opt(12, 30, 45).unwrap(), Some(offset)),
207            expected: serde_json::json!("12:30:45+02:00"),
208        },
209        ValueFixture {
210            name: "datetime",
211            value: CypherValue::DateTime(zoned, Some("Europe/Stockholm".into())),
212            expected: serde_json::json!("2024-03-14T12:30:45+02:00[Europe/Stockholm]"),
213        },
214        ValueFixture {
215            name: "localdatetime",
216            value: CypherValue::LocalDateTime(ndt),
217            expected: serde_json::json!("2024-03-14T12:30:45"),
218        },
219        ValueFixture {
220            name: "duration",
221            value: CypherValue::Duration(IsoDuration::new(0, 0, 3661, 0)),
222            expected: serde_json::json!("PT1H1M1S"),
223        },
224        ValueFixture {
225            name: "point_cartesian",
226            value: CypherValue::Point(PointValue::cartesian_2d(1.0, 2.0)),
227            expected: serde_json::json!({
228                "srid": 7203,
229                "crs": "cartesian",
230                "x": 1.0,
231                "y": 2.0
232            }),
233        },
234        ValueFixture {
235            name: "point_geographic",
236            value: CypherValue::Point(PointValue::wgs84_2d(-73.98, 40.75)),
237            expected: serde_json::json!({
238                "srid": 4326,
239                "crs": "wgs-84",
240                "longitude": -73.98,
241                "latitude": 40.75
242            }),
243        },
244        ValueFixture {
245            name: "geometry",
246            value: CypherValue::Geometry(GeometryValue::LineString {
247                coordinates: vec![[0.0, 0.0], [1.0, 1.0]],
248                srid: 7203,
249            }),
250            expected: serde_json::json!({
251                "type": "LineString",
252                "coordinates": [[0.0, 0.0], [1.0, 1.0]]
253            }),
254        },
255        ValueFixture {
256            name: "vector",
257            value: CypherValue::Vector {
258                coord: VectorCoordKind::Float32,
259                dim: 3,
260                values: vec![
261                    CypherValue::Float(1.0),
262                    CypherValue::Float(2.0),
263                    CypherValue::Float(3.0),
264                ],
265            },
266            expected: serde_json::json!({
267                "type": "FLOAT32",
268                "dim": 3,
269                "values": [1.0, 2.0, 3.0]
270            }),
271        },
272    ]
273}
274
275/// A stats snapshot exercising all 11 counters — including a deliberate
276/// zero (`labels_removed`) to pin "zeros are included" — paired with its
277/// expected wire JSON.
278pub fn stats_fixture() -> (WireStatsSnapshot, Value) {
279    let snap = WireStatsSnapshot {
280        nodes_created: 3,
281        nodes_deleted: 1,
282        relationships_created: 2,
283        relationships_deleted: 1,
284        properties_set: 5,
285        labels_added: 4,
286        labels_removed: 0,
287        indexes_added: 1,
288        indexes_removed: 1,
289        constraints_added: 2,
290        constraints_removed: 1,
291    };
292    let expected = serde_json::json!({
293        "nodes_created": 3,
294        "nodes_deleted": 1,
295        "relationships_created": 2,
296        "relationships_deleted": 1,
297        "properties_set": 5,
298        "labels_added": 4,
299        "labels_removed": 0,
300        "indexes_added": 1,
301        "indexes_removed": 1,
302        "constraints_added": 2,
303        "constraints_removed": 1
304    });
305    (snap, expected)
306}
307
308/// The ADR-0224 `columnTypes` of the golden row: one
309/// [`crate::wire::column_type_name`] per column, in column order. The
310/// golden row IS the first row, so this derivation is the fixture's
311/// `columnTypes` array — surfaces reproducing the envelope call this
312/// instead of re-deriving it.
313pub fn column_types(row: &IndexMap<String, CypherValue>) -> Vec<String> {
314    row.values()
315        .map(|v| crate::wire::column_type_name(v).to_string())
316        .collect()
317}
318
319/// One result row exercising every variant, plus the expected full success
320/// envelope for it — the canonical ADR-0491 shape, timing split included.
321/// Columns are the fixture names, in order. Any surface that assembles a
322/// response from [`value_to_wire_json`], [`stats_to_wire_json`], and
323/// [`response_envelope`] must reproduce this envelope exactly — including
324/// the ADR-0224 `columnTypes` array, one [`crate::wire::column_type_name`]
325/// per column, in column order ([`column_types`]), and the ADR-0491 timing
326/// block, by passing [`FIXTURE_TIMING_STAMP`] to [`response_envelope`].
327pub fn golden_row() -> (Vec<String>, IndexMap<String, CypherValue>, Value) {
328    let fixtures = value_fixtures();
329    let columns: Vec<String> = fixtures.iter().map(|f| f.name.to_string()).collect();
330    let mut row = IndexMap::new();
331    let mut row_json = Map::new();
332    for f in &fixtures {
333        row.insert(f.name.to_string(), f.value.clone());
334        row_json.insert(f.name.to_string(), f.expected.clone());
335    }
336    let (_snap, stats_expected) = stats_fixture();
337
338    let mut envelope = Map::new();
339    envelope.insert(
340        "columns".into(),
341        Value::Array(columns.iter().map(|c| Value::String(c.clone())).collect()),
342    );
343    // ADR-0224: the engine stamps each column from the first row; the golden
344    // row IS the first row, so callers reproduce the fixture by passing
345    // `column_types(&row)` to `response_envelope`.
346    let column_type_names: Vec<Value> = column_types(&row).into_iter().map(Value::String).collect();
347    envelope.insert("columnTypes".into(), Value::Array(column_type_names));
348    envelope.insert("rows".into(), Value::Array(vec![Value::Object(row_json)]));
349    envelope.insert("stats".into(), stats_expected);
350    // ADR-0363 decision 9: the success envelope always carries the list;
351    // this fixture is a plain run, so it is empty.
352    envelope.insert(
353        notification_keys::NOTIFICATIONS.into(),
354        Value::Array(Vec::new()),
355    );
356    // ADR-0221 + ADR-0491: the engine-reported elapsed together with its
357    // PARSE / PLAN / EXECUTE split; the fixture pins the shape with the
358    // fixed stamp, so callers reproduce the fixture by passing
359    // `FIXTURE_TIMING_STAMP` to `response_envelope`.
360    envelope.insert(
361        "elapsed_ms".into(),
362        Value::from(FIXTURE_TIMING_STAMP.elapsed_ms),
363    );
364    envelope.insert(
365        "parse_ms".into(),
366        Value::from(FIXTURE_TIMING_STAMP.parse_ms),
367    );
368    envelope.insert("plan_ms".into(), Value::from(FIXTURE_TIMING_STAMP.plan_ms));
369    envelope.insert(
370        "execute_ms".into(),
371        Value::from(FIXTURE_TIMING_STAMP.execute_ms),
372    );
373    // LABS-1120: the fine sub-split and the plan-cache outcome, from the
374    // same fixed stamp.
375    envelope.insert(
376        "lex_parse_ms".into(),
377        Value::from(FIXTURE_TIMING_STAMP.lex_parse_ms),
378    );
379    envelope.insert(
380        "rewrite_ms".into(),
381        Value::from(FIXTURE_TIMING_STAMP.rewrite_ms),
382    );
383    envelope.insert(
384        "lower_ms".into(),
385        Value::from(FIXTURE_TIMING_STAMP.lower_ms),
386    );
387    envelope.insert(
388        "result_generation_ms".into(),
389        Value::from(FIXTURE_TIMING_STAMP.result_generation_ms),
390    );
391    envelope.insert(
392        "plan_cache".into(),
393        Value::from(FIXTURE_TIMING_STAMP.plan_cache),
394    );
395    // LABS-418: the structured plan document is always present, `null` on a
396    // plain run.
397    envelope.insert("plan".into(), Value::Null);
398    envelope.insert("error".into(), Value::Null);
399
400    (columns, row, Value::Object(envelope))
401}
402
403/// The canonical wire envelope for a **write-only** statement (a
404/// `CREATE`/`MERGE`/`SET`/… without `RETURN`): no result columns, and the
405/// single empty driving row the engine seeds must render as an **empty**
406/// `rows` array — never `[{}]`. Returns the raw `(columns, rows, stats)` a
407/// surface would hand to [`rows_for_result`]/[`response_envelope`] plus the
408/// expected full envelope (with ADR-0224 `"columnTypes": []` — no columns,
409/// so no column types — and the ADR-0491 timing block, by passing
410/// [`FIXTURE_TIMING_STAMP`] to [`response_envelope`]), so every surface can
411/// pin the empty-columns envelope-assembly path (which the value fixtures
412/// never exercise).
413pub fn envelope_write_only() -> (
414    Vec<String>,
415    Vec<IndexMap<String, CypherValue>>,
416    WireStatsSnapshot,
417    Value,
418) {
419    // No columns, one empty driving row — exactly what the engine yields for
420    // a top-level write with no RETURN.
421    let columns: Vec<String> = Vec::new();
422    let rows = vec![IndexMap::new()];
423    let stats = WireStatsSnapshot {
424        nodes_created: 1,
425        labels_added: 1,
426        ..Default::default()
427    };
428    let expected = serde_json::json!({
429        "columns": [],
430        // ADR-0224: no columns, so no column types.
431        "columnTypes": [],
432        "rows": [],
433        "stats": {
434            "nodes_created": 1,
435            "nodes_deleted": 0,
436            "relationships_created": 0,
437            "relationships_deleted": 0,
438            "properties_set": 0,
439            "labels_added": 1,
440            "labels_removed": 0,
441            "indexes_added": 0,
442            "indexes_removed": 0,
443            "constraints_added": 0,
444            "constraints_removed": 0
445        },
446        // ADR-0363 decision 9: always present, empty on a plain run.
447        (notification_keys::NOTIFICATIONS): [],
448        // ADR-0221 + ADR-0491: the fixed stamp's total and split, together.
449        "elapsed_ms": FIXTURE_TIMING_STAMP.elapsed_ms,
450        "parse_ms": FIXTURE_TIMING_STAMP.parse_ms,
451        "plan_ms": FIXTURE_TIMING_STAMP.plan_ms,
452        "execute_ms": FIXTURE_TIMING_STAMP.execute_ms,
453        "lex_parse_ms": FIXTURE_TIMING_STAMP.lex_parse_ms,
454        "rewrite_ms": FIXTURE_TIMING_STAMP.rewrite_ms,
455        "lower_ms": FIXTURE_TIMING_STAMP.lower_ms,
456        "result_generation_ms": FIXTURE_TIMING_STAMP.result_generation_ms,
457        "plan_cache": FIXTURE_TIMING_STAMP.plan_cache,
458        // LABS-418: always present, null on a plain run.
459        "plan": null,
460        "error": null
461    });
462    (columns, rows, stats, expected)
463}
464
465/// Assert a candidate value serializer reproduces the canonical wire JSON
466/// for every fixture. Surfaces call this with their own
467/// `&CypherValue -> serde_json::Value` function so drift becomes a test
468/// failure; surfaces pass [`value_to_wire_json`] itself to prove
469/// the shared module is reachable and correct from each surface's build.
470pub fn assert_all_match<F>(serialize: F)
471where
472    F: Fn(&CypherValue) -> Value,
473{
474    for f in value_fixtures() {
475        let got = serialize(&f.value);
476        assert_eq!(
477            got, f.expected,
478            "wire encoding drift for fixture `{}`:\n  got:      {}\n  expected: {}",
479            f.name, got, f.expected
480        );
481    }
482}