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