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