1use serde_json::{json, Map, Value};
18
19use super::notification_wire::notification_fields;
20use crate::wire::Notification;
21use crate::wire::{plan_node_wire, PlanMetricsWire, PlanNodeWire};
22use crate::CypherValue;
23
24pub const SCHEMA: &str = "relate.plan/v1";
26
27pub fn plan_document(
48 tree: &CypherValue,
49 statement: Option<&str>,
50 notifications: &[Notification],
51) -> Value {
52 let totals = crate::wire::plan_subtree_totals(tree);
56 let warnings_by_operator = operator_warnings(notifications);
60 let operator_scoped = warnings_by_operator.values().map(Vec::len).sum::<usize>();
61 let mut joined = 0;
67 let (root, profiled) = node_json(
68 &plan_node_wire(tree),
69 &totals,
70 &warnings_by_operator,
71 &mut joined,
72 );
73 assert_eq!(
78 joined, operator_scoped,
79 "every operator-scoped notification joins exactly one plan node (ADR-0363, ADR-0381): \
80 {operator_scoped} stamped, {joined} joined"
81 );
82 json!({
83 "schema": SCHEMA,
84 "profiled": profiled,
85 "statement": statement,
86 "root": root,
87 })
88}
89
90fn operator_warnings(notifications: &[Notification]) -> crate::IndexMap<usize, Vec<&Notification>> {
94 let mut by_operator: crate::IndexMap<usize, Vec<&Notification>> = crate::IndexMap::new();
95 for notification in notifications {
96 if let Some(operator_id) = notification.operator_id() {
97 by_operator
98 .entry(operator_id)
99 .or_default()
100 .push(notification);
101 }
102 }
103 by_operator
104}
105
106fn node_json(
112 node: &PlanNodeWire<'_>,
113 totals: &crate::IndexMap<i64, i64>,
114 warnings_by_operator: &crate::IndexMap<usize, Vec<&Notification>>,
115 joined: &mut usize,
116) -> (Value, bool) {
117 let mut profiled = node.metrics.is_some();
121 let children: Vec<Value> = node
122 .children
123 .iter()
124 .map(|child| {
125 let (child_json, child_profiled) =
126 node_json(&plan_node_wire(child), totals, warnings_by_operator, joined);
127 profiled |= child_profiled;
128 child_json
129 })
130 .collect();
131 let loops = node.input_rows();
136 let mut out = Map::new();
137 out.insert("operator".to_string(), json!(node.operator_type));
138 out.insert("details".to_string(), json!(node.details));
139 out.insert(
140 "identifiers".to_string(),
141 Value::Array(node.identifiers.iter().map(|name| json!(name)).collect()),
142 );
143 out.insert("estimated_rows".to_string(), json!(node.estimated_rows));
144 out.insert(
145 "actual".to_string(),
146 match &node.metrics {
147 Some(metrics) => {
148 let facts = crate::wire::profiled_facts(*metrics, totals, node.id);
152 actual_json(&facts.metrics, facts.total_time_ns, loops)
153 }
154 None => Value::Null,
155 },
156 );
157 let (fused_into, fused_metrics) = fused_fields(node);
163 out.insert("fused_into".to_string(), fused_into);
164 out.insert("fused_metrics".to_string(), fused_metrics);
165 out.insert("children".to_string(), Value::Array(children));
166 let operator_id = node.operator_id();
177 let warnings = warnings_by_operator
178 .get(&operator_id)
179 .map(Vec::as_slice)
180 .unwrap_or_default();
181 *joined += warnings.len();
182 out.insert(
183 "warnings".to_string(),
184 Value::Array(
185 warnings
186 .iter()
187 .map(|notification| Value::Object(notification_fields(notification)))
188 .collect(),
189 ),
190 );
191 (Value::Object(out), profiled)
192}
193
194fn fused_fields(node: &PlanNodeWire<'_>) -> (Value, Value) {
198 match node.fused {
199 Some(fused) => (
200 json!(fused.parent),
201 fused.metrics.map_or(Value::Null, |m| {
202 json!({
203 "seek_ms": crate::wire::time_ns_ms(m.seek_ns),
204 "node_reads": m.node_reads,
205 })
206 }),
207 ),
208 None => (Value::Null, Value::Null),
209 }
210}
211
212fn actual_json(metrics: &PlanMetricsWire, subtree_ns: i64, loops: Option<u64>) -> Value {
218 let mut out = Map::new();
219 out.insert("rows".to_string(), json!(metrics.rows));
220 out.insert(
221 "time_ms".to_string(),
222 json!(crate::wire::time_ns_ms(metrics.time_ns)),
223 );
224 out.insert(
225 "total_time_ms".to_string(),
226 json!(crate::wire::time_ns_ms(subtree_ns)),
227 );
228 out.insert("db_hits".to_string(), json!(metrics.db_hits));
229 out.insert(
236 "seek_ms".to_string(),
237 json!(crate::wire::time_ns_ms(metrics.phases.seek_ns)),
238 );
239 out.insert(
240 "walk_ms".to_string(),
241 json!(crate::wire::time_ns_ms(metrics.phases.walk_ns)),
242 );
243 out.insert("loops".to_string(), json!(loops));
247 out.insert("memory_bytes".to_string(), json!(metrics.memory_bytes));
248 out.insert(
251 "expression_built_bytes".to_string(),
252 json!(metrics.expression_built_bytes),
253 );
254 out.insert("hops".to_string(), json!(metrics.reads.hops));
255 out.insert(
256 "neighbor_walks".to_string(),
257 json!(metrics.reads.neighbor_walks),
258 );
259 out.insert("node_reads".to_string(), json!(metrics.reads.node_reads));
260 out.insert("batched".to_string(), json!(metrics.batched));
265 out.insert("zone_skips".to_string(), json!(metrics.zone_skips));
269 out.insert(
276 "frontier".to_string(),
277 json!({
278 "edge_visits": metrics.frontier.edge_visits,
279 "levels": metrics.frontier.levels,
280 "endpoints": metrics.frontier.endpoints,
281 "cells": metrics.frontier.cells,
282 "memo_hits": metrics.frontier.memo_hits,
283 "memo_misses": metrics.frontier.memo_misses,
284 "representative_proofs": metrics.frontier.representative_proofs,
285 "search_proven": metrics.frontier.search_proven,
286 "search_disproven": metrics.frontier.search_disproven,
287 "declined_exhausted": metrics.frontier.declined_exhausted,
288 "budget_fraction": metrics.frontier.budget_fraction,
289 }),
290 );
291 out.insert(
295 "frontier_decline".to_string(),
296 json!(metrics.frontier_decline),
297 );
298 if let Some(memo) = metrics.memo {
304 let mut group = json!({
305 "probes": memo.probes,
306 "hits": memo.hits,
307 "inserts": memo.inserts,
308 "refused": memo.refused,
309 "bytes": memo.bytes,
310 "disabled_count": memo.disabled_count,
311 });
312 if !memo.kinds.is_empty() {
313 group["kinds"] = json!(memo.kinds.names().collect::<Vec<_>>());
314 }
315 out.insert("memo".to_string(), group);
316 }
317 out.insert(
321 "start".to_string(),
322 match &metrics.start {
323 Some(start) => json!({
324 "element": start.element,
325 "backward": start.backward,
326 "reason": start.reason,
327 }),
328 None => Value::Null,
329 },
330 );
331 out.insert(
334 "kernel".to_string(),
335 match metrics.kernel {
336 Some(rung) => json!({"rung": rung.as_str(), "hops": rung.hops()}),
337 None => Value::Null,
338 },
339 );
340 Value::Object(out)
341}
342
343#[cfg(test)]
344mod tests {
345 use super::*;
346 use crate::wire::plan_test_fixtures::{plan_seek_wire_node, plan_wire_node};
347
348 #[test]
349 fn actual_carries_the_subtree_total() {
350 let scan = plan_wire_node("NodeByLabelScan", 1, Some(3_000_000), vec![]);
351 let root = plan_wire_node("ProduceResults", 0, Some(10_000_000), vec![scan]);
352 let doc = plan_document(&root, Some("MATCH (n) RETURN n"), &[]);
353 assert_eq!(doc["profiled"], true);
354 assert_eq!(
355 doc["root"]["actual"]["time_ms"], 10.0,
356 "the root's own time renders in milliseconds"
357 );
358 assert_eq!(
359 doc["root"]["actual"]["total_time_ms"], 13.0,
360 "the root's total covers itself plus the scan: 10 + 3 = 13 ms"
361 );
362 let child = &doc["root"]["children"][0];
363 assert_eq!(
364 child["actual"]["total_time_ms"], 3.0,
365 "a leaf's total equals its own time"
366 );
367 let explain = plan_document(
369 &plan_wire_node("ProduceResults", 0, None, vec![]),
370 Some("RETURN 1"),
371 &[],
372 );
373 assert!(explain["root"]["actual"].is_null());
374 }
375
376 #[test]
382 fn actual_carries_the_phase_times_and_loops() {
383 let scan = plan_wire_node("NodeByLabelScan", 1, Some(3_000_000), vec![]);
384 let root = plan_wire_node("ProduceResults", 0, Some(10_000_000), vec![scan]);
385 let doc = plan_document(&root, Some("MATCH (n) RETURN n"), &[]);
386 assert_eq!(doc["root"]["actual"]["seek_ms"], 0.0);
389 assert_eq!(doc["root"]["actual"]["walk_ms"], 0.0);
390 assert_eq!(doc["root"]["actual"]["loops"], 1, "the scan's rows");
394 let child = &doc["root"]["children"][0];
395 assert!(child["actual"]["loops"].is_null());
396 }
397
398 #[test]
401 fn actual_carries_the_memo_group_only_when_used() {
402 use crate::wire::plan_keys;
403 let scan = plan_wire_node("NodeByLabelScan", 1, Some(3_000_000), vec![]);
404 let mut root = plan_wire_node("ProduceResults", 0, Some(10_000_000), vec![scan]);
405 let doc = plan_document(&root, Some("MATCH (n) RETURN n"), &[]);
406 assert!(doc["root"]["actual"].get("memo").is_none());
407 let CypherValue::Map(node) = &mut root else {
408 unreachable!()
409 };
410 let Some(CypherValue::Map(args)) = node.get_mut(plan_keys::ARGS) else {
411 unreachable!()
412 };
413 for (key, value) in [
414 (plan_keys::MEMO_PROBES, 100),
415 (plan_keys::MEMO_HITS, 90),
416 (plan_keys::MEMO_INSERTS, 10),
417 (plan_keys::MEMO_REFUSED, 0),
418 (plan_keys::MEMO_BYTES, 1024),
419 (plan_keys::MEMO_DISABLED_COUNT, 1),
420 ] {
421 args.insert(key.to_string(), CypherValue::Int(value));
422 }
423 args.insert(
424 plan_keys::MEMO_KINDS.to_string(),
425 CypherValue::List(vec![CypherValue::Str("datetime".into())]),
426 );
427 let doc = plan_document(&root, Some("MATCH (n) RETURN n"), &[]);
428 assert_eq!(
429 doc["root"]["actual"]["memo"],
430 json!({"probes": 100, "hits": 90, "inserts": 10, "refused": 0,
431 "bytes": 1024, "disabled_count": 1, "kinds": ["datetime"]})
432 );
433 assert!(doc["root"]["children"][0]["actual"].get("memo").is_none());
434 }
435
436 #[test]
437 fn projects_the_document_shape() {
438 let doc = plan_document(
439 &plan_wire_node("ProduceResults", 0, None, vec![]),
440 Some("RETURN 1"),
441 &[],
442 );
443 assert_eq!(doc["schema"], SCHEMA);
444 assert_eq!(doc["profiled"], false);
445 assert_eq!(doc["root"]["operator"], "ProduceResults");
446 assert_eq!(doc["root"]["identifiers"][0], "name");
447 assert!(
448 doc["root"]["warnings"].is_array(),
449 "warnings always present"
450 );
451 assert!(doc["root"]["actual"].is_null());
452 }
453
454 #[test]
459 fn the_seek_operators_project_into_the_document() {
460 let seek = plan_seek_wire_node(
461 "NodeIndexSeekByRange",
462 "RANGE INDEX n:User(age) WHERE age > 5, WHERE filter",
463 5,
464 1,
465 );
466 let root = plan_wire_node("ProduceResults", 0, None, vec![seek]);
467 let doc = plan_document(&root, Some("MATCH (n:User) WHERE n.age > 5 RETURN n"), &[]);
468 let node = &doc["root"]["children"][0];
469 assert_eq!(node["operator"], "NodeIndexSeekByRange");
470 assert_eq!(
471 node["details"],
472 "RANGE INDEX n:User(age) WHERE age > 5, WHERE filter"
473 );
474 assert_eq!(node["estimated_rows"], 5);
475 assert!(
476 node["actual"].is_null(),
477 "an EXPLAIN-shaped seek node carries no metrics"
478 );
479 }
480
481 #[test]
485 fn a_fused_child_projects_its_parent_and_seek_pair() {
486 use crate::wire::plan_test_fixtures::fused_seek_wire_node;
487
488 let child = fused_seek_wire_node(2, 1, 2_000_000, 3);
489 let parent = plan_wire_node("NodeIndexSeek", 1, None, vec![child]);
490 let doc = plan_document(
491 &plan_wire_node("ProduceResults", 0, None, vec![parent]),
492 None,
493 &[],
494 );
495 let parent = &doc["root"]["children"][0];
496 assert!(parent["fused_into"].is_null());
497 assert!(parent["fused_metrics"].is_null());
498 let child = &parent["children"][0];
499 assert_eq!(child["fused_into"], 1);
500 assert_eq!(child["fused_metrics"]["seek_ms"], 2.0);
501 assert_eq!(child["fused_metrics"]["node_reads"], 3);
502 assert!(child["actual"].is_null());
503 }
504
505 #[test]
506 fn node_warnings_are_the_canonical_notification_projection() {
507 use crate::wire::{notification_keys, notification_to_wire_json, NotificationKind};
508
509 let notification =
510 Notification::new(NotificationKind::CartesianProduct, "no join predicate")
511 .with_operator_id(1);
512 let tree = plan_wire_node(
513 "ProduceResults",
514 0,
515 None,
516 vec![plan_wire_node("CartesianProduct", 1, None, vec![])],
517 );
518 let doc = plan_document(
519 &tree,
520 Some("MATCH (a), (b) RETURN a, b"),
521 std::slice::from_ref(¬ification),
522 );
523
524 let warning = &doc["root"]["children"][0]["warnings"][0];
525 let mut canonical = notification_to_wire_json(¬ification);
526 canonical
527 .as_object_mut()
528 .expect("the canonical notification is an object")
529 .remove(notification_keys::OPERATOR_ID);
530 assert_eq!(
531 *warning, canonical,
532 "the node warning is the canonical notification object minus the join key"
533 );
534 assert!(
535 warning.get(notification_keys::OPERATOR_ID).is_none(),
536 "the node scopes the operator, so the join key is not repeated"
537 );
538 assert_eq!(doc["root"]["warnings"], json!([]));
539 }
540
541 #[test]
542 #[should_panic(expected = "plan wire Id is non-negative")]
543 fn negative_operator_id_is_a_loud_wire_break() {
544 let tree = plan_wire_node("ProduceResults", -1, None, vec![]);
545 let _ = plan_document(&tree, Some("RETURN 1"), &[]);
546 }
547
548 #[test]
549 #[should_panic(expected = "every operator-scoped notification joins exactly one plan node")]
550 fn an_unjoined_operator_notification_is_a_loud_wire_break() {
551 use crate::wire::NotificationKind;
552
553 let notification =
554 Notification::new(NotificationKind::CartesianProduct, "no join predicate")
555 .with_operator_id(7);
556 let tree = plan_wire_node("ProduceResults", 0, None, vec![]);
557 let _ = plan_document(&tree, Some("RETURN 1"), &[notification]);
558 }
559}