Skip to main content

relate_model/
plan_wire.rs

1//! The structured query plan wire form (ADR-0344/0345): the typed plan
2//! node accessor and the plan contract the presentation and the engine's
3//! warning construction read (ADR-0400 — the table layout itself lives
4//! with its one consumer in the formatter) — one spelling so no surface
5//! can drift from the wire form it reads. The key vocabulary lives in its
6//! own module (`plan_keys.rs`), and the typed warning vocabulary beside it
7//! (LABS-461: `plan_warning.rs`), parsed here by the node accessor.
8
9use super::plan_args::{
10    metric_group_ints, metric_set_ints, optional_bool, optional_fraction, optional_int,
11};
12use super::plan_keys;
13use super::plan_metrics_wire::{
14    KernelRungWire, PlanExpandIntoWire, PlanFrontierWire, PlanHashJoinWire, PlanInTxWire,
15    PlanMetricsWire, PlanPhasesWire, PlanProfiledFacts, PlanReadsWire, PlanStartWire,
16    PlanVectorScanWire,
17};
18use super::plan_warning::PlanWarning;
19use crate::CypherValue;
20
21// ---------------------------------------------------------------------------
22// Structured query plan wire form (ADR-0344/0345)
23// ---------------------------------------------------------------------------
24
25/// The one spelling of a plan column's unavailable value, shared by every
26/// presentation of the plan table (the engine renderer and the surfaces'
27/// table layout) so "column not produced" renders identically everywhere.
28pub const PLAN_UNAVAILABLE: &str = "-";
29
30// The PROFILE metric-wire family — the rung enum, the metric set, the
31// read-kind/phase/start/frontier/IN-TRANSACTIONS shapes it composes, and
32// the profiled-facts presentation bundle — lives in its own module
33// beside this one (`plan_metrics_wire.rs`, REL8-2047's split), like the
34// fused-child, memo and warning shapes; the node wire form below reads
35// it here.
36
37/// The typed view of one structured-plan wire node (ADR-0344/0345): the
38/// producer (`relate`'s `PlanNode::to_value`) emits exactly this
39/// shape, so this accessor states the invariants instead of tolerating
40/// misses — a malformed plan fails loudly rather than silently dropping
41/// a row or shifting cells into the wrong column.
42pub struct PlanNodeWire<'a> {
43    pub operator_type: &'a str,
44    pub id: i64,
45    pub details: &'a str,
46    pub estimated_rows: Option<i64>,
47    /// The ladder level behind `estimated_rows` (ADR-0708); present
48    /// exactly when the estimate is.
49    pub estimate_provenance: Option<crate::wire::EstimateProvenance>,
50    /// PROFILE metrics (ADR-0344 phase 2 + metric fields): rows
51    /// produced, elapsed time, store accesses, and row-materialization
52    /// bytes — present only on PROFILE trees: the producer always emits
53    /// the four `args` metric fields together, so a half-present set is
54    /// a wire-contract break that fails loudly.
55    pub metrics: Option<PlanMetricsWire>,
56    /// The node's args map, validated by the accessor (a map, present): a
57    /// consumer reshaping the node (the HTTP Query API v2 plan) reads its
58    /// display and identity entries from here rather than re-matching the
59    /// raw map, so the invariant is stated once.
60    pub args: &'a crate::IndexMap<String, CypherValue>,
61    /// The identifier names the operator introduces, validated as strings
62    /// at the accessor: the producer always emits the key as a list of
63    /// strings, so a miss, a non-list or a non-string element is a
64    /// wire-contract break that fails loudly here — the one place the
65    /// invariant lives, never a per-consumer element check.
66    pub identifiers: Vec<&'a str>,
67    /// The child nodes' raw wire values — the consumer recurses through
68    /// [`plan_node_wire`] itself, so the typed view stays shallow.
69    pub children: &'a [CypherValue],
70    /// The typed warnings the node carries (typed node warnings): parsed
71    /// into the one [`PlanWarning`] vocabulary — an entry outside it (or
72    /// a payload shape its variant does not carry) is a wire-contract
73    /// break that fails loudly at the accessor, never a silently
74    /// dropped warning.
75    pub warnings: Vec<PlanWarning>,
76    /// The fused virtual child fact (virtual plan operators): `Some` on
77    /// a display-only breakdown step of its fused parent operator, never
78    /// an executed one — the parent link and the step's own measured
79    /// pair (the seek step's seek-phase time and node reads; `None` on a
80    /// hop step, which no real per-hop counter measures) travel
81    /// together, so the half-states are unrepresentable. Never the
82    /// parent's rows, time or memory.
83    pub fused: Option<super::plan_fused::FusedChildWire>,
84    /// The batched `CALL { … } IN TRANSACTIONS` body role marker
85    /// (REL8-2047): the `CallSubquery` parent's id on the root of a body
86    /// subtree, `None` on every node of the statement's own pipeline —
87    /// the role fact [`Self::input_rows`] and [`Self::executed_children`]
88    /// read so a body operator is never taken for the data-flow child.
89    pub body_of: Option<i64>,
90}
91
92impl PlanNodeWire<'_> {
93    /// The operator's id as the width the notification side stamps
94    /// (`Notification::operator_id`): the wire carries the engine's `usize`
95    /// `PlanNode.id` as an `i64` (narrowed by the saturating `metric_i64`
96    /// on serialize), so this is the one place the join key is widened
97    /// back. A negative id is a wire-contract break and fails loudly, like
98    /// the accessor's other non-negative integer fields — never a silent
99    /// wrap that drops the operator's warnings.
100    pub(crate) fn operator_id(&self) -> usize {
101        usize::try_from(self.id).expect("plan wire Id is non-negative (ADR-0345)")
102    }
103}
104
105/// The `planner-impl` value every surface sends (ADR-0357): this engine's
106/// own planner, named honestly — never Neo4j's `IDP`/`COST`, which would
107/// claim a planner this engine does not run.
108pub const NEO4J_PLANNER_IMPL: &str = "relate";
109
110/// The Cypher language version the plan's `version` arg reports (ADR-0357):
111/// this engine's front-end is openCypher 5-compatible (ADR-0046), so the
112/// Neo4j-shaped `version` arg says `5` — the language version, not a
113/// product version.
114pub const CYPHER_VERSION: &str = "5";
115
116/// One all-or-none counter group of a PROFILE node, decoded: absent →
117/// the default (no such work ran), present on a PROFILE node → `build` over
118/// the values in the group's wire order, present anywhere else (or
119/// partial, which [`metric_group_ints`] rejects) → the wire-contract
120/// break, kept loud. One decoder for every group; a new group is a table
121/// row, not another copy of this match.
122fn decode_metric_group<const N: usize, T: Default>(
123    args: &crate::IndexMap<String, CypherValue>,
124    has_metrics: bool,
125    keys: [&'static str; N],
126    build: impl FnOnce([i64; N]) -> T,
127) -> T {
128    match (has_metrics, metric_group_ints(args, keys)) {
129        (_, None) => T::default(),
130        (true, Some(ints)) => build(ints),
131        (has_metrics, ints) => panic!(
132            "plan wire {}..{} are non-negative integers emitted together, only on a PROFILE node, got metrics={has_metrics} ints={ints:?}",
133            keys[0],
134            keys[N - 1]
135        ),
136    }
137}
138
139/// Read one plan wire node (ADR-0344/0345). Panics on a malformed node —
140/// the wire form is engine-produced and invariant-bound, so a deviation
141/// is an engine contract break, kept loud like every other boundary here.
142pub fn plan_node_wire(value: &CypherValue) -> PlanNodeWire<'_> {
143    let CypherValue::Map(node) = value else {
144        panic!("plan wire node is a map, got {value:?}")
145    };
146    let operator_type = match node.get(plan_keys::OPERATOR_TYPE) {
147        Some(CypherValue::Str(op)) => op.as_str(),
148        other => panic!(
149            "plan wire node carries a string {} (ADR-0345), got {other:?}",
150            plan_keys::OPERATOR_TYPE
151        ),
152    };
153    let args = match node.get(plan_keys::ARGS) {
154        Some(CypherValue::Map(args)) => args,
155        other => panic!(
156            "plan wire node carries a map {} (ADR-0345), got {other:?}",
157            plan_keys::ARGS
158        ),
159    };
160    let id = match args.get(plan_keys::ID) {
161        Some(CypherValue::Int(id)) => *id,
162        other => panic!(
163            "plan wire node carries an integer {} (ADR-0345), got {other:?}",
164            plan_keys::ID
165        ),
166    };
167    let details = match args.get(plan_keys::DETAILS) {
168        Some(CypherValue::Str(details)) => details.as_str(),
169        other => panic!(
170            "plan wire node carries a string {} (ADR-0345), got {other:?}",
171            plan_keys::DETAILS
172        ),
173    };
174    let estimated_rows = optional_int(args, plan_keys::ESTIMATED_ROWS);
175    let estimate_provenance = match (estimated_rows, args.get(plan_keys::ESTIMATE_PROVENANCE)) {
176        (None, None) => None,
177        (Some(rows), None) => panic!(
178            "plan wire node carries {} only with {} (ADR-0708), got {rows} alone",
179            plan_keys::ESTIMATED_ROWS,
180            plan_keys::ESTIMATE_PROVENANCE
181        ),
182        (Some(_), Some(CypherValue::Str(name))) => Some(
183            crate::wire::EstimateProvenance::from_name(name.as_str()).unwrap_or_else(|| {
184                panic!(
185                    "plan wire node carries a known {} (ADR-0708), got {name:?}",
186                    plan_keys::ESTIMATE_PROVENANCE
187                )
188            }),
189        ),
190        (estimate, other) => panic!(
191            "plan wire node carries {} only with {} as a string (ADR-0708), got {other:?} beside {estimate:?}",
192            plan_keys::ESTIMATE_PROVENANCE,
193            plan_keys::ESTIMATED_ROWS
194        ),
195    };
196    // Virtual plan operators: the fused fact gates the metric groups — a
197    // fused child carries only the step's own measured pair, so the
198    // ride-along groups (the phase times, the read kinds) stay the fused
199    // parent's and never parse here.
200    let fused = super::plan_fused::fused_child(args);
201    // REL8-2047: the body role marker, the fused fact's optional-int
202    // shape — its presence is the whole "this node is a batched body's
203    // operator" fact. Like a fused child, a body operator runs inside its
204    // parent's batch, so it never carries the PROFILE metric block
205    // (ADR-0681): a half-state here is rejected loudly, never silently
206    // summed into the parent's subtree total.
207    let body_of = optional_int(args, plan_keys::BODY_OF);
208    if body_of.is_some() {
209        for key in plan_keys::METRIC_BLOCK_KEYS.iter() {
210            if args.contains_key(*key) {
211                panic!(
212                    "plan wire node carries {} beside {} (REL8-2047): a batched \
213                     body operator's work is its CallSubquery parent's batch \
214                     record, so it never carries the metric block",
215                    key,
216                    plan_keys::BODY_OF
217                );
218            }
219        }
220    }
221    // The metric block's five scalar keys ride the module's one all-or-none
222    // group policy ([`plan_keys::METRIC_BLOCK_KEYS`]); their presence *is*
223    // the metric-set fact. A fused child's parser already rejected them.
224    let scalars = metric_group_ints(args, plan_keys::METRIC_BLOCK_KEYS);
225    let has_metrics = scalars.is_some();
226    // LABS-448: the phase times ride the metric set with the kinds,
227    // through the one group policy.
228    let phases = if fused.is_some() {
229        PlanPhasesWire::default()
230    } else {
231        metric_set_ints(
232            args,
233            [plan_keys::SEEK_TIME_NS, plan_keys::WALK_TIME_NS],
234            has_metrics,
235        )
236        .map(|[seek_ns, walk_ns]| PlanPhasesWire { seek_ns, walk_ns })
237        .unwrap_or_default()
238    };
239    // LABS-369: the read-kind mix rides the metric set, through the one
240    // group policy the phase times share — one spelling, never a
241    // hand-rolled copy per field family.
242    let reads = if fused.is_some() {
243        PlanReadsWire::default()
244    } else {
245        metric_set_ints(
246            args,
247            [
248                plan_keys::HOPS,
249                plan_keys::NEIGHBOR_WALKS,
250                plan_keys::NODE_READS,
251            ],
252            has_metrics,
253        )
254        .map(|[hops, neighbor_walks, node_reads]| PlanReadsWire {
255            hops,
256            neighbor_walks,
257            node_reads,
258        })
259        .unwrap_or_default()
260    };
261    // The walk's chosen start (LABS-369): the element, direction and
262    // reason class, present only when the clause walked a pattern —
263    // emitted together, like the metric set.
264    let start = {
265        let element = optional_int(args, plan_keys::START_ELEMENT);
266        let backward = optional_bool(args, plan_keys::START_BACKWARD);
267        let reason = match args.get(plan_keys::START_REASON) {
268            None => None,
269            Some(CypherValue::Str(reason)) => Some(
270                match plan_keys::REASONS.iter().find(|r| **r == reason.as_str()) {
271                    Some(name) => *name,
272                    None => panic!(
273                        "plan wire {} is one of {:?} (LABS-369), got {reason:?}",
274                        plan_keys::START_REASON,
275                        plan_keys::REASONS
276                    ),
277                },
278            ),
279            other => panic!(
280                "plan wire {} is a string when present (LABS-369), got {other:?}",
281                plan_keys::START_REASON
282            ),
283        };
284        match (has_metrics, element, backward, reason) {
285            (_, None, None, None) => None,
286            (true, Some(element), Some(backward), Some(reason)) => Some(PlanStartWire {
287                element,
288                backward,
289                reason,
290            }),
291            (has_metrics, element, backward, reason) => panic!(
292                "plan wire {}, {} and {} are emitted together, only on a \
293                 PROFILE node (LABS-369), got metrics={has_metrics} \
294                 element={element:?} backward={backward:?} reason={reason:?}",
295                plan_keys::START_ELEMENT,
296                plan_keys::START_BACKWARD,
297                plan_keys::START_REASON
298            ),
299        }
300    };
301    // Which rung served the clause's MATCH walk (LABS-1117): the typed
302    // name, validated against the one vocabulary like the start reasons —
303    // present only on a PROFILE node, and only when a rung served it. The
304    // chain's hop count is its own arg, and the typed value makes the
305    // half-state (a chain rung without it) unrepresentable past this
306    // parse: a chain without hops, hops beside another rung, or hops
307    // alone are all kept loud.
308    let kernel = match (has_metrics, args.get(plan_keys::KERNEL_RUNG)) {
309        (_, None) => {
310            if optional_int(args, plan_keys::KERNEL_HOPS).is_some() {
311                panic!(
312                    "plan wire {} rides only the {} key (LABS-1117)",
313                    plan_keys::KERNEL_HOPS,
314                    plan_keys::KERNEL_RUNG
315                );
316            }
317            None
318        }
319        (true, Some(CypherValue::Str(name))) => {
320            // The three payload-free rungs each reject a stray hop count;
321            // the chain builds its `Chain { hops }` once from the arg.
322            let payload_free = |rung: KernelRungWire| {
323                if let Some(hops) = optional_int(args, plan_keys::KERNEL_HOPS) {
324                    panic!(
325                        "plan wire {} rides only the {} rung (LABS-1117), \
326                         got rung={} hops={hops:?}",
327                        plan_keys::KERNEL_HOPS,
328                        KernelRungWire::CHAIN,
329                        rung.as_str()
330                    );
331                }
332                Some(rung)
333            };
334            match name.as_str() {
335                KernelRungWire::CHAIN => match optional_int(args, plan_keys::KERNEL_HOPS) {
336                    Some(hops) => Some(KernelRungWire::Chain { hops }),
337                    other => panic!(
338                        "plan wire {} is a non-negative integer when {} is {} \
339                         (LABS-1117), got {other:?}",
340                        plan_keys::KERNEL_HOPS,
341                        plan_keys::KERNEL_RUNG,
342                        KernelRungWire::CHAIN
343                    ),
344                },
345                KernelRungWire::FRONTIER_NFA => payload_free(KernelRungWire::FrontierNfa),
346                KernelRungWire::WALKER => payload_free(KernelRungWire::Walker),
347                other => panic!(
348                    "plan wire {} is one of {:?} (LABS-1117), got {other:?}",
349                    plan_keys::KERNEL_RUNG,
350                    plan_keys::KERNEL_RUNGS
351                ),
352            }
353        }
354        (has_metrics, other) => panic!(
355            "plan wire {} is a string when present, only on a PROFILE \
356             node (LABS-1117), got metrics={has_metrics} value={other:?}",
357            plan_keys::KERNEL_RUNG
358        ),
359    };
360    // Whether the clause ran ADR-0468's batch scan/filter/project chain
361    // (LABS-359): the producer emits the key only when true (never a
362    // `false` beside the absent fact), and only on a PROFILE node.
363    let batched = match (has_metrics, args.get(plan_keys::BATCHED)) {
364        (_, None) => false,
365        (true, Some(CypherValue::Bool(true))) => true,
366        (has_metrics, other) => panic!(
367            "plan wire {} is true, only on a PROFILE node (ADR-0468, \
368             LABS-359), got metrics={has_metrics} value={other:?}",
369            plan_keys::BATCHED
370        ),
371    };
372    // The batch filter's zone skips (LABS-645): emitted only when nonzero,
373    // and only on a PROFILE node.
374    let zone_skips = match (has_metrics, optional_int(args, plan_keys::ZONE_SKIPS)) {
375        (_, None) => 0,
376        (true, Some(skips)) => skips,
377        (has_metrics, other) => panic!(
378            "plan wire {} is a non-negative integer, only on a PROFILE \
379             node (LABS-645), got metrics={has_metrics} value={other:?}",
380            plan_keys::ZONE_SKIPS
381        ),
382    };
383    let expand_into = decode_metric_group(
384        args,
385        has_metrics,
386        plan_keys::EXPAND_INTO_GROUP_KEYS,
387        |[probes, reversed]| PlanExpandIntoWire {
388            probes: metric_u64(probes),
389            reversed: metric_u64(reversed),
390        },
391    );
392    let hash_join = decode_metric_group(
393        args,
394        has_metrics,
395        plan_keys::HASH_JOIN_GROUP_KEYS,
396        |[build_rows, probe_rows, semi_mask_rejected]| PlanHashJoinWire {
397            build_rows: metric_u64(build_rows),
398            probe_rows: metric_u64(probe_rows),
399            semi_mask_rejected: metric_u64(semi_mask_rejected),
400        },
401    );
402    let vector_scan = decode_metric_group(
403        args,
404        has_metrics,
405        plan_keys::VECTOR_SCAN_GROUP_KEYS,
406        |[matrix, value_scan]| PlanVectorScanWire {
407            matrix: metric_u64(matrix),
408            value_scan: metric_u64(value_scan),
409        },
410    );
411    // The frontier family's run counters (ADR-0478) with the NFA rung's
412    // own facts: the producer emits the ten integers and the budget
413    // fraction together, only when the family ran the clause, and only
414    // on a PROFILE node — anything else is a wire-contract break, kept
415    // loud like the batched flag's and the start trio's half-states.
416    let frontier = {
417        let ints = metric_group_ints(args, plan_keys::FRONTIER_GROUP_KEYS);
418        let fraction = optional_fraction(args, plan_keys::FRONTIER_BUDGET_FRACTION);
419        match (has_metrics, ints, fraction) {
420            (_, None, None) => PlanFrontierWire::default(),
421            (
422                true,
423                Some(
424                    [edge_visits, levels, endpoints, cells, memo_hits, memo_misses, representative_proofs, search_proven, search_disproven, declined_exhausted],
425                ),
426                Some(budget_fraction),
427            ) => PlanFrontierWire {
428                edge_visits,
429                levels,
430                endpoints,
431                cells,
432                memo_hits,
433                memo_misses,
434                representative_proofs,
435                search_proven,
436                search_disproven,
437                declined_exhausted,
438                budget_fraction,
439            },
440            (has_metrics, ints, fraction) => panic!(
441                "plan wire {}..{} are non-negative integers emitted \
442                 together with {}, only on a PROFILE node (ADR-0478, \
443                 ADR-0516), got metrics={has_metrics} ints={ints:?} \
444                 fraction={fraction:?}",
445                plan_keys::FRONTIER_EDGES,
446                plan_keys::FRONTIER_DECLINED_EXHAUSTED,
447                plan_keys::FRONTIER_BUDGET_FRACTION
448            ),
449        }
450    };
451    // The frontier rung's run-time decline (ADR-0516), present only when
452    // the rung engaged, ran, and fell through — the typed reason's
453    // stable wire name, validated against the one vocabulary like the
454    // start reasons.
455    let frontier_decline = match (has_metrics, args.get(plan_keys::FRONTIER_DECLINE_REASON)) {
456        (_, None) => None,
457        (true, Some(CypherValue::Str(reason))) => Some(
458            match plan_keys::DECLINE_REASONS
459                .iter()
460                .find(|name| **name == reason.as_str())
461            {
462                Some(name) => *name,
463                None => panic!(
464                    "plan wire {} is one of {:?} (ADR-0516), got {reason:?}",
465                    plan_keys::FRONTIER_DECLINE_REASON,
466                    plan_keys::DECLINE_REASONS
467                ),
468            },
469        ),
470        (has_metrics, other) => panic!(
471            "plan wire {} is a string when present, only on a PROFILE \
472             node (ADR-0516), got metrics={has_metrics} value={other:?}",
473            plan_keys::FRONTIER_DECLINE_REASON
474        ),
475    };
476    // The expression-memo group (ADR-0654), read and validated by its
477    // own module.
478    let memo = super::plan_memo::memo_group(args, has_metrics);
479    // The `IN TRANSACTIONS` batch facts (REL8-2047): the producer emits
480    // the seven integers together, only when the arm ran batches and only
481    // on a PROFILE node — the all-or-none group read, kept loud like the
482    // frontier family's.
483    let intx = decode_metric_group(
484        args,
485        has_metrics,
486        plan_keys::IN_TX_GROUP_KEYS,
487        |[batches, committed, rolled_back, peak_input_rows_bytes, peak_output_rows_bytes, peak_scratch_bytes, peak_wal_bytes]| {
488            PlanInTxWire {
489                batches,
490                committed,
491                rolled_back,
492                peak_input_rows_bytes,
493                peak_output_rows_bytes,
494                peak_scratch_bytes,
495                peak_wal_bytes,
496            }
497        },
498    );
499    // The scalar group already enforced all-or-none and non-negative; the
500    // wire form has one shape here, derived from the group read above.
501    let metrics = scalars.map(
502        |[rows, time_ns, db_hits, memory_bytes, expression_built_bytes]| PlanMetricsWire {
503            rows,
504            time_ns,
505            db_hits,
506            memory_bytes,
507            expression_built_bytes,
508            reads,
509            phases,
510            start,
511            kernel,
512            batched,
513            zone_skips,
514            frontier,
515            frontier_decline,
516            memo,
517            intx,
518            expand_into,
519            hash_join,
520            vector_scan,
521        },
522    );
523    let children = match node.get(plan_keys::CHILDREN) {
524        None => &[],
525        Some(CypherValue::List(children)) => children.as_slice(),
526        other => panic!(
527            "plan wire {} is a list when present (ADR-0345), got {other:?}",
528            plan_keys::CHILDREN
529        ),
530    };
531    // The typed warnings (typed node warnings): warning maps — the
532    // vocabulary name and, when the warning carries one, its payload —
533    // anything else is a wire-contract break kept loud.
534    let warnings = match node.get(plan_keys::WARNINGS) {
535        None => Vec::new(),
536        Some(CypherValue::List(items)) => items
537            .iter()
538            .map(|item| {
539                let CypherValue::Map(warning) = item else {
540                    panic!(
541                        "plan wire {} entries are warning maps, got {item:?}",
542                        plan_keys::WARNINGS
543                    )
544                };
545                let name = match warning.get(plan_keys::WARNING_NAME) {
546                    Some(CypherValue::Str(name)) => name.as_str(),
547                    other => panic!(
548                        "plan wire warning {} is a string, got {other:?}",
549                        plan_keys::WARNING_NAME
550                    ),
551                };
552                let index = match warning.get(plan_keys::WARNING_INDEX) {
553                    None => None,
554                    Some(CypherValue::Str(index)) => Some(index.as_str()),
555                    other => panic!(
556                        "plan wire warning {} is a string when present, got {other:?}",
557                        plan_keys::WARNING_INDEX
558                    ),
559                };
560                // The one validating match into the typed vocabulary: the
561                // name must come from it, carrying the payload shape its
562                // variant carries. A miss is a contract break kept loud,
563                // never a silently dropped or reinterpreted warning.
564                PlanWarning::from_wire_parts(name, index).unwrap_or_else(|| {
565                    panic!(
566                        "plan wire warnings come from the typed vocabulary \
567                         (ADR-0344 typed node warnings) with the payload shape \
568                         their variant carries, got {name:?}"
569                    )
570                })
571            })
572            .collect(),
573        other => panic!(
574            "plan wire {} is a list of warning maps when present, got {other:?}",
575            plan_keys::WARNINGS
576        ),
577    };
578    // The producer always writes the identifiers key as a list: a miss or
579    // a non-list is a wire-contract break, kept loud like the node's own
580    // shape (the consumer reshaping the node reads them from the typed
581    // view, never re-matching the raw map).
582    let identifiers: Vec<&str> = match node.get(plan_keys::IDENTIFIERS) {
583        Some(CypherValue::List(identifiers)) => identifiers
584            .iter()
585            .map(|identifier| match identifier {
586                CypherValue::Str(name) => name.as_str(),
587                other => panic!(
588                    "a plan wire node's {} element is a string (ADR-0345), got {other:?}",
589                    plan_keys::IDENTIFIERS
590                ),
591            })
592            .collect(),
593        other => panic!(
594            "plan wire node carries a list {} (ADR-0345), got {other:?}",
595            plan_keys::IDENTIFIERS
596        ),
597    };
598    PlanNodeWire {
599        operator_type,
600        id,
601        details,
602        estimated_rows,
603        estimate_provenance,
604        metrics,
605        args,
606        identifiers,
607        children,
608        warnings,
609        fused,
610        body_of,
611    }
612}
613
614/// The one subtree-total pass (cumulative vs self): every node's own
615/// elapsed time plus every descendant's, saturated through the metric
616/// width policy — ONE walk over the tree, keyed by the node's pre-order
617/// id, so the table's walk and the agent document's walk read the same
618/// map instead of each re-folding its subtree (one policy, one spelling).
619/// Reads the typed accessor (the same validation every other consumer
620/// takes), so a malformed tree fails loudly here rather than silently
621/// summing partial subtrees.
622pub fn plan_subtree_totals(plan: &CypherValue) -> crate::IndexMap<i64, i64> {
623    let mut totals = crate::IndexMap::new();
624    subtree_total_into(plan, &mut totals);
625    totals
626}
627
628/// The pass's recursion: a node's own time plus its children's totals,
629/// inserted under the node's id and returned as the parent's summand —
630/// the saturation lands once per node (`metric_i64` into the map), never
631/// an i64→u64→u128 round-trip on the way up.
632fn subtree_total_into(plan: &CypherValue, totals: &mut crate::IndexMap<i64, i64>) -> u128 {
633    let node = plan_node_wire(plan);
634    let own = node
635        .metrics
636        .map_or(0u128, |m| metric_u64(m.time_ns) as u128);
637    let children = node
638        .children
639        .iter()
640        .map(|child| subtree_total_into(child, totals))
641        .fold(0u128, u128::saturating_add);
642    let sum = own.saturating_add(children);
643    totals.insert(node.id, metric_i64(sum));
644    sum
645}
646
647/// The wire form's one width policy for metric integers: saturate at
648/// `i64::MAX` — one policy for every metric field (rows and time
649/// alike), never an unchecked cast on one and a clamp on the other.
650pub fn metric_i64(value: u128) -> i64 {
651    value.min(i64::MAX as u128) as i64
652}
653/// The consumer side of the metric width policy: a wire metric is
654/// non-negative when present (the producer saturates), so the
655/// one conversion every metric cell reads goes through here — never a
656/// bare `as` cast at a call site.
657pub fn metric_u64(value: i64) -> u64 {
658    value.max(0) as u64
659}
660/// The one nanoseconds-to-milliseconds conversion, as a float: every
661/// millisecond presentation reads it — the table cell's `{:.3}` render,
662/// the HTTP v2 node's `time` field, the agent document's `time_ms` and
663/// `total_time_ms` — so the spellings cannot drift (and none truncates
664/// a sub-millisecond operator to 0).
665pub fn time_ns_ms(time_ns: i64) -> f64 {
666    metric_u64(time_ns) as f64 / 1e6
667}
668
669/// A metrics-carrying node's presentation bundle, read from the totals
670/// map — the ONE spelling of the pairing's contract ("the map covers
671/// every walked node"), so the table's walk and the agent document's
672/// walk cannot each re-state the lookup, and a third consumer inherits
673/// it instead of cloning the panic.
674pub fn profiled_facts(
675    metrics: PlanMetricsWire,
676    totals: &crate::IndexMap<i64, i64>,
677    id: i64,
678) -> PlanProfiledFacts {
679    PlanProfiledFacts {
680        metrics,
681        total_time_ns: *totals
682            .get(&id)
683            .unwrap_or_else(|| panic!("the totals map covers every walked node, id {id}")),
684    }
685}
686
687impl<'a> PlanNodeWire<'a> {
688    /// The node's input-row count (LABS-343's structural fact): the first
689    /// child's produced rows — the bottom-up nesting puts each earlier
690    /// clause under the one it feeds — `None` when the node has no input
691    /// child (the statement's one seed row). The one spelling, read by
692    /// the plan walk and the flag fold alike.
693    pub fn input_rows(&self) -> Option<u64> {
694        // The data-flow child is the first executed child
695        // ([`Self::is_executed_child`]): a `CALL { … } IN TRANSACTIONS`
696        // as the clause with no preceding clause carries only a body
697        // child, whose rows are not this operator's input.
698        self.executed_children()
699            .next()
700            .and_then(|child| child.metrics.map(|m| metric_u64(m.rows)))
701    }
702
703    /// Whether this node is an executed child of its parent — the one
704    /// child-role rule both walks read. Two child roles are skipped: a
705    /// display-only fused breakdown step (ADR-0622), whose measured pair
706    /// is a phase of the fused parent's clause totals, and a batched
707    /// `CALL { … } IN TRANSACTIONS` body's operator root (REL8-2047),
708    /// whose work is the `CallSubquery` operator's batch record.
709    pub fn is_executed_child(&self) -> bool {
710        self.fused.is_none() && self.body_of.is_none()
711    }
712
713    /// The node's executed children: every child
714    /// [`Self::is_executed_child`] admits — the one skip policy, so a
715    /// walk reading executed operators or their PROFILE metrics never
716    /// counts a display-only fused step or a batched body's operators a
717    /// second time.
718    pub fn executed_children(&self) -> impl Iterator<Item = PlanNodeWire<'a>> + 'a {
719        self.children
720            .iter()
721            .map(plan_node_wire)
722            .filter(|child| child.is_executed_child())
723    }
724}
725
726#[cfg(test)]
727mod tests {
728    use super::*;
729    use crate::wire::plan_test_fixtures::{args_mut, plan_seek_wire_node, plan_wire_node};
730
731    /// LABS-1117: a chain rung without its hop count is the same
732    /// half-state the start trio rejects — the strict parse fails loudly
733    /// instead of accepting a rung the contract says carries its count.
734    #[test]
735    #[should_panic(
736        expected = "plan wire KernelHops is a non-negative integer when KernelRung is chain"
737    )]
738    fn a_chain_rung_without_its_hop_count_fails_the_parse() {
739        let mut node = plan_wire_node("Match", 0, Some(1), vec![]);
740        args_mut(&mut node).insert(
741            plan_keys::KERNEL_RUNG.to_string(),
742            CypherValue::Str("chain".into()),
743        );
744        let _ = plan_node_wire(&node);
745    }
746
747    /// ADR-0705: the vector-scan group decodes to the typed pair on a
748    /// PROFILE node, the group's two keys in the vocabulary's wire order.
749    #[test]
750    fn the_vector_scan_group_decodes_to_the_typed_pair() {
751        let mut node = plan_wire_node("Match", 0, Some(1), vec![]);
752        for (key, count) in plan_keys::VECTOR_SCAN_GROUP_KEYS.into_iter().zip([2, 0]) {
753            args_mut(&mut node).insert(key.to_string(), CypherValue::Int(count));
754        }
755        let wire = plan_node_wire(&node);
756        let scans = wire.metrics.expect("a PROFILE node").vector_scan;
757        assert_eq!((scans.matrix, scans.value_scan), (2, 0));
758    }
759
760    /// A node with no vector scan decodes to the default pair, and the
761    /// group's two keys are distinct names (a copied key would alias them).
762    #[test]
763    fn a_node_without_the_vector_scan_group_decodes_to_zeros() {
764        let node = plan_wire_node("Match", 0, Some(1), vec![]);
765        let scans = plan_node_wire(&node)
766            .metrics
767            .expect("a PROFILE node")
768            .vector_scan;
769        assert_eq!((scans.matrix, scans.value_scan), (0, 0));
770        let [matrix, value] = plan_keys::VECTOR_SCAN_GROUP_KEYS;
771        assert_ne!(matrix, value);
772    }
773
774    /// Half the group is the wire-contract break every other group keeps
775    /// loud: the producer emits the pair together.
776    #[test]
777    #[should_panic(expected = "are an all-or-none group")]
778    fn half_a_vector_scan_group_fails_the_parse() {
779        let mut node = plan_wire_node("Match", 0, Some(1), vec![]);
780        args_mut(&mut node).insert(
781            plan_keys::VECTOR_SCAN_MATRIX.to_string(),
782            CypherValue::Int(1),
783        );
784        let _ = plan_node_wire(&node);
785    }
786
787    /// The one subtree-total pass (cumulative vs self): a node's own time
788    /// plus every descendant's — the leaf equals its own time, the root
789    /// sums the pipeline, an inner node's total lands under its id, and an
790    /// unprofiled subtree contributes zero.
791    #[test]
792    fn subtree_totals_map_the_tree() {
793        // root(10) -> [scan(3), filter(2) -> [expand(5)]]: the root's
794        // total is 10 + 3 + 2 + 5 = 20; the filter heads the expand.
795        let expand = plan_wire_node("Expand", 3, Some(5), vec![]);
796        let filter = plan_wire_node("Filter", 2, Some(2), vec![expand]);
797        let scan = plan_wire_node("NodeByLabelScan", 1, Some(3), vec![]);
798        let root = plan_wire_node("ProduceResults", 0, Some(10), vec![scan, filter]);
799        let totals = plan_subtree_totals(&root);
800        assert_eq!(totals[&0], 20, "the root's total covers the pipeline");
801        assert_eq!(totals[&2], 7, "the filter's total heads the expand");
802        assert_eq!(totals[&1], 3, "a leaf's total equals its own time");
803        // An unprofiled node contributes nothing — an EXPLAIN tree's
804        // totals are zero, never a fabricated number.
805        let explain = plan_subtree_totals(&plan_wire_node("ProduceResults", 0, None, vec![]));
806        assert_eq!(explain[&0], 0);
807    }
808
809    /// ADR-0486: the index-seek operators ride the wire like every other
810    /// operator — no operator-specific mapping anywhere in the form — the
811    /// typed accessor reading `NodeIndexSeekByRange` with its seek-line
812    /// details and its own count as the estimate.
813    #[test]
814    fn the_seek_operators_ride_the_wire_form() {
815        let seek = plan_seek_wire_node(
816            "NodeIndexSeekByRange",
817            "RANGE INDEX n:User(age) WHERE age > 5, WHERE filter",
818            5,
819            1,
820        );
821        let point = plan_seek_wire_node(
822            "NodeIndexSeek",
823            "RANGE INDEX n:Person(name) WHERE name = 'Alice'",
824            1,
825            2,
826        );
827        let root = plan_wire_node("ProduceResults", 0, None, vec![seek, point]);
828        let wire = plan_node_wire(&root);
829        assert_eq!(wire.operator_type, "ProduceResults");
830        let window = plan_node_wire(&wire.children[0]);
831        assert_eq!(window.operator_type, "NodeIndexSeekByRange");
832        assert_eq!(
833            window.details,
834            "RANGE INDEX n:User(age) WHERE age > 5, WHERE filter"
835        );
836        assert_eq!(window.estimated_rows, Some(5));
837        let read = plan_node_wire(&wire.children[1]);
838        assert_eq!(read.operator_type, "NodeIndexSeek");
839        assert_eq!(
840            read.details,
841            "RANGE INDEX n:Person(name) WHERE name = 'Alice'"
842        );
843        assert_eq!(read.estimated_rows, Some(1));
844    }
845}