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