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