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