Skip to main content

relate_model/
agent_plan.rs

1//! The agent-native plan projection (`relate.plan/v1`, LABS-370): the
2//! engine's plan wire form projected onto the stable, snake_case schema
3//! our own bindings hand out — real numbers, no `args` nesting, warnings
4//! carrying the engine's remedy-bearing notifications.
5//!
6//! This is *our* API dialect, deliberately distinct from the Neo4j-facing
7//! projection the Bolt and HTTP surfaces emit (ADR-0357, ADR-0365), which
8//! mirrors Neo4j's own node shape for its tooling. Both read the same
9//! engine wire form through the one typed accessor
10//! ([`plan_node_wire`](crate::wire::plan_node_wire)); neither re-matches
11//! the raw map.
12//!
13//! Schema stability: the document carries its `schema` identifier
14//! (`relate.plan/v1`); a breaking shape change bumps the version and
15//! ships its own ADR. Fields are added, never renamed in place.
16
17use 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
24/// The schema identifier every projected document carries.
25pub const SCHEMA: &str = "relate.plan/v1";
26
27/// Project a plan wire tree (the engine's `PlanNode::to_value()` form)
28/// into the agent-native document, as a `serde_json::Value` — the surface
29/// serializes it, exactly as it does the sibling wire documents
30/// (`stats_to_wire_json`, `notifications_to_wire_json`).
31///
32/// `statement` is the planned statement as echoed (`None` for a
33/// hand-built tree); `notifications` is the result's remedy-bearing
34/// notification list (ADR-0363), joined into each node's `warnings` by the
35/// operator id the engine stamps — so an agent reads the diagnosis and the
36/// action beside it. `profiled` is derived from the walked tree itself —
37/// any node carrying runtime metrics makes it a `PROFILE` tree — so the
38/// top-level flag can never contradict the per-node `actual` objects.
39///
40/// # Panics
41///
42/// Panics when the value is not a plan wire tree — the same contract
43/// [`plan_node_wire`] enforces (a wire break is an engine bug, never
44/// silently dropped) — and when an operator-scoped notification stamps an
45/// id no walked node carries, so a warning can never vanish from the
46/// document.
47pub fn plan_document(
48    tree: &CypherValue,
49    statement: Option<&str>,
50    notifications: &[Notification],
51) -> Value {
52    // The subtree totals, one pass over the tree (the one map every
53    // node's `total_time_ms` reads — the same spelling the table's walk
54    // uses, never a second fold).
55    let totals = crate::wire::plan_subtree_totals(tree);
56    // The flat notification list, indexed by operator id in one pass: each
57    // node's `warnings` is then a lookup, never a re-scan of the whole list
58    // per node.
59    let warnings_by_operator = operator_warnings(notifications);
60    let operator_scoped = warnings_by_operator.values().map(Vec::len).sum::<usize>();
61    // The one walk: `node_json` validates each node once (through the
62    // typed accessor) and reports whether its subtree carries runtime
63    // metrics, which is exactly `profiled` — never a second pass and never
64    // a caller-supplied flag that could disagree with the `actual` objects.
65    // It also counts the notifications that joined a node.
66    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    // Every operator-scoped notification belongs to a node of the walked
74    // tree; a stamp that matches no node (or matches two) is a
75    // wire-contract break that fails loudly, never a warning silently
76    // dropped from the document.
77    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
90/// The flat notification list grouped by the operator id each entry
91/// stamps — built in one pass, the index every node's `warnings` lookup
92/// reads. Statement-scoped entries (no operator id) have no node to join.
93fn 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
106/// One operator node's document: the display facts, the estimate, the
107/// runtime metrics when the tree is profiled, the typed warnings, and the
108/// children — each read from the validated typed view, never a raw match.
109/// One node's document plus whether its subtree carries runtime metrics
110/// (the fact `profiled` is derived from, reported by the same walk).
111fn 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    // The children walk first: each child reports whether its subtree
118    // carries runtime metrics (the fact `profiled` derives from), by the
119    // same single walk.
120    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    // LABS-448: the arm's iteration count — the input clause's rows (the
132    // child operator's `Rows`, the number the table shows one cell up),
133    // named here for consumers that do not walk children. `None` when the
134    // node has no input child (the statement's seed row).
135    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                // The bundle — the one pairing helper in wire, the same
149                // spelling the table's walk reads, never a second fold or
150                // a re-stated contract here.
151                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    // Virtual plan operators: a display-only fused child names its fused
158    // parent operator's id and, on a PROFILE seek step, its own measured
159    // pair; both are always present, `null` on every real operator — the
160    // document's one absence spelling. A fused child's `actual` stays
161    // `null`: the clause's totals are the parent's.
162    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    // The operator's warnings: the remedy-bearing notifications raised for
167    // it (ADR-0363), looked up by the operator id the engine stamps — the
168    // diagnosis and the actionable remedy beside it, which is what makes
169    // the document agent-actionable. Each warning is the canonical
170    // notification projection minus the join key the node already scopes,
171    // so the two spellings cannot drift. Always present, `[]` when none:
172    // one absence spelling in the document.
173    //
174    // The id is widened once, through the typed accessor: a malformed id
175    // fails there even when the result carries no notification to join.
176    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
194/// The fused-child pair of a node's document: the parent operator's id and
195/// the seek step's measured `{seek_ms, node_reads}`. Each is `null` where
196/// the node carries none — every real operator, and a hop step's metrics.
197fn 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
212/// The runtime metrics of a profiled node: rows, the operator's own time
213/// in milliseconds (through the wire's one conversion), the subtree total
214/// of that time (cumulative vs self — the node plus every descendant, the
215/// cost of the sub-pipeline it heads), store accesses, the read-kind mix,
216/// and the walk's chosen start when the operator walked one.
217fn 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    // LABS-448: the phase times behind the read kinds — the seek (the
230    // candidate resolution and admission `node_reads` counts) and the walk
231    // (the relationship traversal `hops`/`neighbor_walks` count),
232    // inclusive of a multi-element pattern's nested phases. The kinds
233    // themselves stay where they are; the phases add only the time
234    // attribution, never a second spelling of a count.
235    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    // LABS-448: the arm's iteration count — always present, `null` when
244    // the node has no input child (the seed row), the one absence
245    // spelling the document uses.
246    out.insert("loops".to_string(), json!(loops));
247    out.insert("memory_bytes".to_string(), json!(metrics.memory_bytes));
248    // ADR-0463: expression allocation bytes, beside the row-materialization
249    // bytes — the two allocation facts PROFILE reports separately.
250    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    // ADR-0468 (LABS-359): whether the operator ran the batch
261    // scan/filter/project chain over `Chunk` — always present, `false`
262    // on every operator the chain declined, so a consumer never faces a
263    // missing-key rule.
264    out.insert("batched".to_string(), json!(metrics.batched));
265    // LABS-645: the batch filter's zone skips — always present, `0` on
266    // every operator that skipped nothing, the same never-missing-key
267    // rule.
268    out.insert("zone_skips".to_string(), json!(metrics.zone_skips));
269    // ADR-0478: the frontier family's run counters — always present as
270    // the nested set, all zeros on every operator the family declined,
271    // the same never-missing-key rule. The NFA rung's own facts ride
272    // the same object (ADR-0516): the cells, the rule memo's hits and
273    // misses, the admission asks by verdict, and the budget fraction
274    // the rule's work spent.
275    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    // ADR-0516: the frontier rung's run-time decline — always present,
292    // `null` when the rung never declined, the one absence spelling the
293    // document uses (a consumer never faces a missing-key rule).
294    out.insert(
295        "frontier_decline".to_string(),
296        json!(metrics.frontier_decline),
297    );
298    // ADR-0654: the expression-memo counters — unlike the always-present
299    // groups above, present only when a memo was probed on the node (the
300    // plan wire's presence-only rule), so a memo-free plan carries no
301    // `memo` key. `bytes` is the memo tables' allocation, never part of
302    // `memory_bytes`; `kinds` is non-empty on the root only.
303    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    // Always present, `null` when the operator walked no pattern: the one
318    // absence spelling the document uses (a consumer never faces a
319    // missing-key rule).
320    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    // LABS-1117: which rung served the clause's MATCH walk — always
332    // present, `null` when no rung served it (the one absence spelling).
333    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        // An unprofiled tree: no actual, no fabricated total.
368        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    /// The phases and loops (LABS-448): `seek_ms`/`walk_ms` render the
377    /// phase times beside the kinds they attribute (the kinds stay where
378    /// they are — the phases add only the time, never a second count),
379    /// and `loops` names the input clause's rows for consumers that do
380    /// not walk children (`null` at the root, the seed row).
381    #[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        // The fixture emits zero phases: the fields render, always
387        // present, zeros rather than absences.
388        assert_eq!(doc["root"]["actual"]["seek_ms"], 0.0);
389        assert_eq!(doc["root"]["actual"]["walk_ms"], 0.0);
390        // The root's loops is its input child's rows (the scan produced
391        // one); the scan itself has no input child (the seed row), so its
392        // loops is null — the one absence spelling.
393        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    /// ADR-0654: `actual.memo` is present only where the node carries the
399    /// group, snake_case with numbers as numbers, `kinds` on the root.
400    #[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    /// ADR-0486: the index-seek operators project into the agent document
455    /// like every other operator — the name, the seek-line details and the
456    /// seek's own count riding `estimated_rows`, no operator-specific
457    /// projection anywhere in the document.
458    #[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    /// Virtual plan operators: a fused seek child projects its parent id
482    /// and its own measured pair; every real operator reads `null` for
483    /// both, and the child's `actual` stays `null`.
484    #[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(&notification),
522        );
523
524        let warning = &doc["root"]["children"][0]["warnings"][0];
525        let mut canonical = notification_to_wire_json(&notification);
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}