relate_model/wire/envelope.rs
1//! The response-envelope family: the canonical success envelope (with the
2//! ADR-0491 phase-timing split), the error envelope, and the timing stamp
3//! that bundles the total with its split.
4//!
5//! Lives in its own module beside the other wire families (the plan wire
6//! form, the notification wire form), re-exported at the `wire` root so
7//! `wire::response_envelope` stays the one public path.
8
9use serde_json::{Map, Value};
10
11use super::{json_f64, notification_keys, notifications_to_wire_json, Notification};
12
13/// The statement's timing block as one wire value — the wire-side spelling
14/// of the engine's result-header timing stamp: the ADR-0221 wall-clock
15/// total (`elapsed_ms`) together with its always-on PARSE / PLAN / EXECUTE
16/// split (ADR-0491) and the fine sub-split plus the plan-cache outcome
17/// (LABS-1120), flattened to the envelope keys' own milliseconds. Bundled
18/// like the engine bundles its stamp, so an envelope construction site
19/// cannot carry the total without its split — and the canonical builder
20/// stays under `clippy::too_many_arguments`.
21///
22/// PARSE is the front-end parse and lowering; PLAN is binding, logical
23/// planning and the admission classification; EXECUTE is the dispatch —
24/// or, for `EXPLAIN`, the plan render, that path's execute-equivalent
25/// stage. The three are disjoint sub-windows of the window `elapsed_ms`
26/// spans, so their sum never exceeds the total (the inter-stage gaps stay
27/// in the total alone); milliseconds because this is the `elapsed_ms`
28/// family it extends (Bolt's seconds rendering is that surface's own
29/// conversion, per ADR-0491 §3). The LABS-1120 fine sub-windows partition
30/// their coarse phase the same way; `plan_cache` explains a hit's
31/// near-zero parse window.
32#[derive(Clone, Copy, Debug, PartialEq)]
33pub struct TimingStampMs {
34 /// The ADR-0221 wall-clock total, in milliseconds.
35 pub elapsed_ms: f64,
36 /// The PARSE stage, in milliseconds.
37 pub parse_ms: f64,
38 /// The PLAN stage, in milliseconds.
39 pub plan_ms: f64,
40 /// The EXECUTE stage, in milliseconds.
41 pub execute_ms: f64,
42 /// The PARSE stage's lexing-plus-AST-build sub-window, in milliseconds
43 /// (LABS-1120) — zero on a plan-cache hit, which `plan_cache` explains.
44 pub lex_parse_ms: f64,
45 /// The PARSE stage's rewrite sub-window (the CIP-231 resolver), in
46 /// milliseconds (LABS-1120) — zero on a plan-cache hit.
47 pub rewrite_ms: f64,
48 /// The PARSE stage's validation-and-lowering sub-window, in
49 /// milliseconds (LABS-1120) — zero on a plan-cache hit.
50 pub lower_ms: f64,
51 /// The EXECUTE stage's result-generation sub-window, in milliseconds
52 /// (LABS-1120) — zero on the `EXPLAIN` path, whose render is itself
53 /// its result generation.
54 pub result_generation_ms: f64,
55 /// The statement's plan-cache outcome (LABS-1120) as the engine
56 /// enum's own wire spelling (`PlanCacheOutcome::as_str`, kebab-case)
57 /// — never re-spelled here: the engine crate pins the vocabulary
58 /// against its enum with a test, so this field cannot drift from it.
59 pub plan_cache: &'static str,
60}
61
62impl TimingStampMs {
63 /// The nested `timings` object (LABS-1120): every duration key of the
64 /// stamp under one object — the form the surfaces that had no flat
65 /// `elapsed_ms` family before (the CLI machine modes, the HTTP Query
66 /// API v2 envelope) carry, so those envelopes stay forward-compatible
67 /// (a later phase joins the object, never the top level). The
68 /// plan-cache outcome rides **beside** the object, never inside it —
69 /// it is an outcome, not a duration. One builder for every surface, so
70 /// the key set cannot drift between them.
71 pub fn to_timings_json(&self) -> Value {
72 let mut object = Map::new();
73 insert_duration_keys(&mut object, self);
74 Value::Object(object)
75 }
76}
77
78/// The stamp's eight duration keys, each through the one f64 conversion —
79/// THE table, consulted by both wire forms (the nested `timings` object
80/// and the canonical envelope's flat family), so a key can never be added
81/// to one form and not the other (found in review).
82fn insert_duration_keys(object: &mut Map<String, Value>, stamp: &TimingStampMs) {
83 object.insert("elapsed_ms".into(), json_f64(stamp.elapsed_ms));
84 object.insert("parse_ms".into(), json_f64(stamp.parse_ms));
85 object.insert("plan_ms".into(), json_f64(stamp.plan_ms));
86 object.insert("execute_ms".into(), json_f64(stamp.execute_ms));
87 object.insert("lex_parse_ms".into(), json_f64(stamp.lex_parse_ms));
88 object.insert("rewrite_ms".into(), json_f64(stamp.rewrite_ms));
89 object.insert("lower_ms".into(), json_f64(stamp.lower_ms));
90 object.insert(
91 "result_generation_ms".into(),
92 json_f64(stamp.result_generation_ms),
93 );
94}
95
96/// Build the canonical success response envelope (ADR-0491): the one
97/// construction every JSON surface renders — the pre-0491 envelope plus
98/// the statement's per-phase timing split beside `elapsed_ms`.
99///
100/// `{ "columns": [...], "columnTypes": [...], "rows": [...], "stats": {...},
101/// "notifications": [...], "elapsed_ms": <f64>, "parse_ms": <f64>,
102/// "plan_ms": <f64>, "execute_ms": <f64>, "lex_parse_ms": <f64>,
103/// "rewrite_ms": <f64>, "lower_ms": <f64>, "result_generation_ms": <f64>,
104/// "plan_cache": "<outcome>", "plan": {...} | null, "error": null }`.
105/// The `plan` key (LABS-418, ADR-0381) is always present too: the
106/// `relate.plan/v1` document, `null` on a plain run.
107/// `elapsed_ms` is the engine-reported statement elapsed in wall-clock
108/// milliseconds (ADR-0221); `parse_ms`/`plan_ms`/`execute_ms` are its
109/// PARSE / PLAN / EXECUTE split (ADR-0491, see [`TimingStampMs`]) — always
110/// populated on this path, never null, riding the one `timings` parameter
111/// so a construction site cannot carry the total without its split.
112/// `columnTypes` carries the engine-stamped
113/// per-column type names (ADR-0224), beside `columns`, same length and order.
114/// `notifications` is always present — empty on a plain run, populated by
115/// `EXPLAIN`/`PROFILE` (ADR-0363 decision 9) — and its entries are the
116/// engine-native objects `super::notification_to_wire_json` emits.
117pub fn response_envelope(
118 columns: &[String],
119 column_types: &[String],
120 rows: Vec<Value>,
121 stats: Value,
122 notifications: &[Notification],
123 timings: TimingStampMs,
124 plan: Option<Value>,
125) -> Value {
126 let mut obj = Map::new();
127 obj.insert(
128 "columns".into(),
129 Value::Array(columns.iter().map(|c| Value::String(c.clone())).collect()),
130 );
131 // ADR-0224: the engine-stamped per-column type names, beside `columns`.
132 obj.insert(
133 "columnTypes".into(),
134 Value::Array(
135 column_types
136 .iter()
137 .map(|t| Value::String(t.clone()))
138 .collect(),
139 ),
140 );
141 obj.insert("rows".into(), Value::Array(rows));
142 obj.insert("stats".into(), stats);
143 // ADR-0363 decision 9: always present, empty on a plain run.
144 obj.insert(
145 notification_keys::NOTIFICATIONS.into(),
146 notifications_to_wire_json(notifications),
147 );
148 // ADR-0221: the engine-reported statement elapsed, in milliseconds;
149 // ADR-0491: its PARSE / PLAN / EXECUTE split beside it; LABS-1120: the
150 // fine sub-split and the plan-cache outcome — the duration keys from
151 // the one table both wire forms share, the outcome beside them.
152 insert_duration_keys(&mut obj, &timings);
153 obj.insert(
154 "plan_cache".into(),
155 Value::String(timings.plan_cache.into()),
156 );
157 obj.insert("error".into(), Value::Null);
158 // The structured plan document (LABS-418, ADR-0381): always present,
159 // `null` when the statement carried no plan — the same presence policy
160 // `notifications` (ADR-0363) and `columnTypes` (ADR-0224) use, owned by
161 // the canonical builder. The HTTP surface's Neo4j-shaped envelope has
162 // its own builder and its own plan keys.
163 obj.insert("plan".into(), plan.unwrap_or(Value::Null));
164 Value::Object(obj)
165}
166
167/// Build the canonical error response envelope: empty `columns`/`rows`, empty
168/// `stats`, and the error message string under `error`.
169pub fn error_envelope(message: &str) -> Value {
170 let mut obj = Map::new();
171 obj.insert("columns".into(), Value::Array(Vec::new()));
172 obj.insert("rows".into(), Value::Array(Vec::new()));
173 obj.insert("stats".into(), Value::Object(Map::new()));
174 obj.insert("error".into(), Value::String(message.to_string()));
175 Value::Object(obj)
176}