use super::plan_args::{
metric_group_ints, metric_set_ints, optional_bool, optional_fraction, optional_int,
};
use super::plan_keys;
use super::plan_metrics_wire::{
KernelRungWire, PlanExpandIntoWire, PlanFrontierWire, PlanHashJoinWire, PlanInTxWire,
PlanMetricsWire, PlanPhasesWire, PlanProfiledFacts, PlanReadsWire, PlanStartWire,
PlanVectorScanWire,
};
use super::plan_warning::PlanWarning;
use crate::CypherValue;
pub const PLAN_UNAVAILABLE: &str = "-";
pub struct PlanNodeWire<'a> {
pub operator_type: &'a str,
pub id: i64,
pub details: &'a str,
pub estimated_rows: Option<i64>,
pub estimate_provenance: Option<crate::wire::EstimateProvenance>,
pub metrics: Option<PlanMetricsWire>,
pub args: &'a crate::IndexMap<String, CypherValue>,
pub identifiers: Vec<&'a str>,
pub children: &'a [CypherValue],
pub warnings: Vec<PlanWarning>,
pub fused: Option<super::plan_fused::FusedChildWire>,
pub body_of: Option<i64>,
}
impl PlanNodeWire<'_> {
pub(crate) fn operator_id(&self) -> usize {
usize::try_from(self.id).expect("plan wire Id is non-negative (ADR-0345)")
}
}
pub const NEO4J_PLANNER_IMPL: &str = "relate";
pub const CYPHER_VERSION: &str = "5";
fn decode_metric_group<const N: usize, T: Default>(
args: &crate::IndexMap<String, CypherValue>,
has_metrics: bool,
keys: [&'static str; N],
build: impl FnOnce([i64; N]) -> T,
) -> T {
match (has_metrics, metric_group_ints(args, keys)) {
(_, None) => T::default(),
(true, Some(ints)) => build(ints),
(has_metrics, ints) => panic!(
"plan wire {}..{} are non-negative integers emitted together, only on a PROFILE node, got metrics={has_metrics} ints={ints:?}",
keys[0],
keys[N - 1]
),
}
}
pub fn plan_node_wire(value: &CypherValue) -> PlanNodeWire<'_> {
let CypherValue::Map(node) = value else {
panic!("plan wire node is a map, got {value:?}")
};
let operator_type = match node.get(plan_keys::OPERATOR_TYPE) {
Some(CypherValue::Str(op)) => op.as_str(),
other => panic!(
"plan wire node carries a string {} (ADR-0345), got {other:?}",
plan_keys::OPERATOR_TYPE
),
};
let args = match node.get(plan_keys::ARGS) {
Some(CypherValue::Map(args)) => args,
other => panic!(
"plan wire node carries a map {} (ADR-0345), got {other:?}",
plan_keys::ARGS
),
};
let id = match args.get(plan_keys::ID) {
Some(CypherValue::Int(id)) => *id,
other => panic!(
"plan wire node carries an integer {} (ADR-0345), got {other:?}",
plan_keys::ID
),
};
let details = match args.get(plan_keys::DETAILS) {
Some(CypherValue::Str(details)) => details.as_str(),
other => panic!(
"plan wire node carries a string {} (ADR-0345), got {other:?}",
plan_keys::DETAILS
),
};
let estimated_rows = optional_int(args, plan_keys::ESTIMATED_ROWS);
let estimate_provenance = match (estimated_rows, args.get(plan_keys::ESTIMATE_PROVENANCE)) {
(None, None) => None,
(Some(rows), None) => panic!(
"plan wire node carries {} only with {} (ADR-0708), got {rows} alone",
plan_keys::ESTIMATED_ROWS,
plan_keys::ESTIMATE_PROVENANCE
),
(Some(_), Some(CypherValue::Str(name))) => Some(
crate::wire::EstimateProvenance::from_name(name.as_str()).unwrap_or_else(|| {
panic!(
"plan wire node carries a known {} (ADR-0708), got {name:?}",
plan_keys::ESTIMATE_PROVENANCE
)
}),
),
(estimate, other) => panic!(
"plan wire node carries {} only with {} as a string (ADR-0708), got {other:?} beside {estimate:?}",
plan_keys::ESTIMATE_PROVENANCE,
plan_keys::ESTIMATED_ROWS
),
};
let fused = super::plan_fused::fused_child(args);
let body_of = optional_int(args, plan_keys::BODY_OF);
if body_of.is_some() {
for key in plan_keys::METRIC_BLOCK_KEYS.iter() {
if args.contains_key(*key) {
panic!(
"plan wire node carries {} beside {} (REL8-2047): a batched \
body operator's work is its CallSubquery parent's batch \
record, so it never carries the metric block",
key,
plan_keys::BODY_OF
);
}
}
}
let scalars = metric_group_ints(args, plan_keys::METRIC_BLOCK_KEYS);
let has_metrics = scalars.is_some();
let phases = if fused.is_some() {
PlanPhasesWire::default()
} else {
metric_set_ints(
args,
[plan_keys::SEEK_TIME_NS, plan_keys::WALK_TIME_NS],
has_metrics,
)
.map(|[seek_ns, walk_ns]| PlanPhasesWire { seek_ns, walk_ns })
.unwrap_or_default()
};
let reads = if fused.is_some() {
PlanReadsWire::default()
} else {
metric_set_ints(
args,
[
plan_keys::HOPS,
plan_keys::NEIGHBOR_WALKS,
plan_keys::NODE_READS,
],
has_metrics,
)
.map(|[hops, neighbor_walks, node_reads]| PlanReadsWire {
hops,
neighbor_walks,
node_reads,
})
.unwrap_or_default()
};
let start = {
let element = optional_int(args, plan_keys::START_ELEMENT);
let backward = optional_bool(args, plan_keys::START_BACKWARD);
let reason = match args.get(plan_keys::START_REASON) {
None => None,
Some(CypherValue::Str(reason)) => Some(
match plan_keys::REASONS.iter().find(|r| **r == reason.as_str()) {
Some(name) => *name,
None => panic!(
"plan wire {} is one of {:?} (LABS-369), got {reason:?}",
plan_keys::START_REASON,
plan_keys::REASONS
),
},
),
other => panic!(
"plan wire {} is a string when present (LABS-369), got {other:?}",
plan_keys::START_REASON
),
};
match (has_metrics, element, backward, reason) {
(_, None, None, None) => None,
(true, Some(element), Some(backward), Some(reason)) => Some(PlanStartWire {
element,
backward,
reason,
}),
(has_metrics, element, backward, reason) => panic!(
"plan wire {}, {} and {} are emitted together, only on a \
PROFILE node (LABS-369), got metrics={has_metrics} \
element={element:?} backward={backward:?} reason={reason:?}",
plan_keys::START_ELEMENT,
plan_keys::START_BACKWARD,
plan_keys::START_REASON
),
}
};
let kernel = match (has_metrics, args.get(plan_keys::KERNEL_RUNG)) {
(_, None) => {
if optional_int(args, plan_keys::KERNEL_HOPS).is_some() {
panic!(
"plan wire {} rides only the {} key (LABS-1117)",
plan_keys::KERNEL_HOPS,
plan_keys::KERNEL_RUNG
);
}
None
}
(true, Some(CypherValue::Str(name))) => {
let payload_free = |rung: KernelRungWire| {
if let Some(hops) = optional_int(args, plan_keys::KERNEL_HOPS) {
panic!(
"plan wire {} rides only the {} rung (LABS-1117), \
got rung={} hops={hops:?}",
plan_keys::KERNEL_HOPS,
KernelRungWire::CHAIN,
rung.as_str()
);
}
Some(rung)
};
match name.as_str() {
KernelRungWire::CHAIN => match optional_int(args, plan_keys::KERNEL_HOPS) {
Some(hops) => Some(KernelRungWire::Chain { hops }),
other => panic!(
"plan wire {} is a non-negative integer when {} is {} \
(LABS-1117), got {other:?}",
plan_keys::KERNEL_HOPS,
plan_keys::KERNEL_RUNG,
KernelRungWire::CHAIN
),
},
KernelRungWire::FRONTIER_NFA => payload_free(KernelRungWire::FrontierNfa),
KernelRungWire::WALKER => payload_free(KernelRungWire::Walker),
other => panic!(
"plan wire {} is one of {:?} (LABS-1117), got {other:?}",
plan_keys::KERNEL_RUNG,
plan_keys::KERNEL_RUNGS
),
}
}
(has_metrics, other) => panic!(
"plan wire {} is a string when present, only on a PROFILE \
node (LABS-1117), got metrics={has_metrics} value={other:?}",
plan_keys::KERNEL_RUNG
),
};
let batched = match (has_metrics, args.get(plan_keys::BATCHED)) {
(_, None) => false,
(true, Some(CypherValue::Bool(true))) => true,
(has_metrics, other) => panic!(
"plan wire {} is true, only on a PROFILE node (ADR-0468, \
LABS-359), got metrics={has_metrics} value={other:?}",
plan_keys::BATCHED
),
};
let zone_skips = match (has_metrics, optional_int(args, plan_keys::ZONE_SKIPS)) {
(_, None) => 0,
(true, Some(skips)) => skips,
(has_metrics, other) => panic!(
"plan wire {} is a non-negative integer, only on a PROFILE \
node (LABS-645), got metrics={has_metrics} value={other:?}",
plan_keys::ZONE_SKIPS
),
};
let expand_into = decode_metric_group(
args,
has_metrics,
plan_keys::EXPAND_INTO_GROUP_KEYS,
|[probes, reversed]| PlanExpandIntoWire {
probes: metric_u64(probes),
reversed: metric_u64(reversed),
},
);
let hash_join = decode_metric_group(
args,
has_metrics,
plan_keys::HASH_JOIN_GROUP_KEYS,
|[build_rows, probe_rows, semi_mask_rejected]| PlanHashJoinWire {
build_rows: metric_u64(build_rows),
probe_rows: metric_u64(probe_rows),
semi_mask_rejected: metric_u64(semi_mask_rejected),
},
);
let vector_scan = decode_metric_group(
args,
has_metrics,
plan_keys::VECTOR_SCAN_GROUP_KEYS,
|[matrix, value_scan]| PlanVectorScanWire {
matrix: metric_u64(matrix),
value_scan: metric_u64(value_scan),
},
);
let frontier = {
let ints = metric_group_ints(args, plan_keys::FRONTIER_GROUP_KEYS);
let fraction = optional_fraction(args, plan_keys::FRONTIER_BUDGET_FRACTION);
match (has_metrics, ints, fraction) {
(_, None, None) => PlanFrontierWire::default(),
(
true,
Some(
[edge_visits, levels, endpoints, cells, memo_hits, memo_misses, representative_proofs, search_proven, search_disproven, declined_exhausted],
),
Some(budget_fraction),
) => PlanFrontierWire {
edge_visits,
levels,
endpoints,
cells,
memo_hits,
memo_misses,
representative_proofs,
search_proven,
search_disproven,
declined_exhausted,
budget_fraction,
},
(has_metrics, ints, fraction) => panic!(
"plan wire {}..{} are non-negative integers emitted \
together with {}, only on a PROFILE node (ADR-0478, \
ADR-0516), got metrics={has_metrics} ints={ints:?} \
fraction={fraction:?}",
plan_keys::FRONTIER_EDGES,
plan_keys::FRONTIER_DECLINED_EXHAUSTED,
plan_keys::FRONTIER_BUDGET_FRACTION
),
}
};
let frontier_decline = match (has_metrics, args.get(plan_keys::FRONTIER_DECLINE_REASON)) {
(_, None) => None,
(true, Some(CypherValue::Str(reason))) => Some(
match plan_keys::DECLINE_REASONS
.iter()
.find(|name| **name == reason.as_str())
{
Some(name) => *name,
None => panic!(
"plan wire {} is one of {:?} (ADR-0516), got {reason:?}",
plan_keys::FRONTIER_DECLINE_REASON,
plan_keys::DECLINE_REASONS
),
},
),
(has_metrics, other) => panic!(
"plan wire {} is a string when present, only on a PROFILE \
node (ADR-0516), got metrics={has_metrics} value={other:?}",
plan_keys::FRONTIER_DECLINE_REASON
),
};
let memo = super::plan_memo::memo_group(args, has_metrics);
let intx = decode_metric_group(
args,
has_metrics,
plan_keys::IN_TX_GROUP_KEYS,
|[batches, committed, rolled_back, peak_input_rows_bytes, peak_output_rows_bytes, peak_scratch_bytes, peak_wal_bytes]| {
PlanInTxWire {
batches,
committed,
rolled_back,
peak_input_rows_bytes,
peak_output_rows_bytes,
peak_scratch_bytes,
peak_wal_bytes,
}
},
);
let metrics = scalars.map(
|[rows, time_ns, db_hits, memory_bytes, expression_built_bytes]| PlanMetricsWire {
rows,
time_ns,
db_hits,
memory_bytes,
expression_built_bytes,
reads,
phases,
start,
kernel,
batched,
zone_skips,
frontier,
frontier_decline,
memo,
intx,
expand_into,
hash_join,
vector_scan,
},
);
let children = match node.get(plan_keys::CHILDREN) {
None => &[],
Some(CypherValue::List(children)) => children.as_slice(),
other => panic!(
"plan wire {} is a list when present (ADR-0345), got {other:?}",
plan_keys::CHILDREN
),
};
let warnings = match node.get(plan_keys::WARNINGS) {
None => Vec::new(),
Some(CypherValue::List(items)) => items
.iter()
.map(|item| {
let CypherValue::Map(warning) = item else {
panic!(
"plan wire {} entries are warning maps, got {item:?}",
plan_keys::WARNINGS
)
};
let name = match warning.get(plan_keys::WARNING_NAME) {
Some(CypherValue::Str(name)) => name.as_str(),
other => panic!(
"plan wire warning {} is a string, got {other:?}",
plan_keys::WARNING_NAME
),
};
let index = match warning.get(plan_keys::WARNING_INDEX) {
None => None,
Some(CypherValue::Str(index)) => Some(index.as_str()),
other => panic!(
"plan wire warning {} is a string when present, got {other:?}",
plan_keys::WARNING_INDEX
),
};
PlanWarning::from_wire_parts(name, index).unwrap_or_else(|| {
panic!(
"plan wire warnings come from the typed vocabulary \
(ADR-0344 typed node warnings) with the payload shape \
their variant carries, got {name:?}"
)
})
})
.collect(),
other => panic!(
"plan wire {} is a list of warning maps when present, got {other:?}",
plan_keys::WARNINGS
),
};
let identifiers: Vec<&str> = match node.get(plan_keys::IDENTIFIERS) {
Some(CypherValue::List(identifiers)) => identifiers
.iter()
.map(|identifier| match identifier {
CypherValue::Str(name) => name.as_str(),
other => panic!(
"a plan wire node's {} element is a string (ADR-0345), got {other:?}",
plan_keys::IDENTIFIERS
),
})
.collect(),
other => panic!(
"plan wire node carries a list {} (ADR-0345), got {other:?}",
plan_keys::IDENTIFIERS
),
};
PlanNodeWire {
operator_type,
id,
details,
estimated_rows,
estimate_provenance,
metrics,
args,
identifiers,
children,
warnings,
fused,
body_of,
}
}
pub fn plan_subtree_totals(plan: &CypherValue) -> crate::IndexMap<i64, i64> {
let mut totals = crate::IndexMap::new();
subtree_total_into(plan, &mut totals);
totals
}
fn subtree_total_into(plan: &CypherValue, totals: &mut crate::IndexMap<i64, i64>) -> u128 {
let node = plan_node_wire(plan);
let own = node
.metrics
.map_or(0u128, |m| metric_u64(m.time_ns) as u128);
let children = node
.children
.iter()
.map(|child| subtree_total_into(child, totals))
.fold(0u128, u128::saturating_add);
let sum = own.saturating_add(children);
totals.insert(node.id, metric_i64(sum));
sum
}
pub fn metric_i64(value: u128) -> i64 {
value.min(i64::MAX as u128) as i64
}
pub fn metric_u64(value: i64) -> u64 {
value.max(0) as u64
}
pub fn time_ns_ms(time_ns: i64) -> f64 {
metric_u64(time_ns) as f64 / 1e6
}
pub fn profiled_facts(
metrics: PlanMetricsWire,
totals: &crate::IndexMap<i64, i64>,
id: i64,
) -> PlanProfiledFacts {
PlanProfiledFacts {
metrics,
total_time_ns: *totals
.get(&id)
.unwrap_or_else(|| panic!("the totals map covers every walked node, id {id}")),
}
}
impl<'a> PlanNodeWire<'a> {
pub fn input_rows(&self) -> Option<u64> {
self.executed_children()
.next()
.and_then(|child| child.metrics.map(|m| metric_u64(m.rows)))
}
pub fn is_executed_child(&self) -> bool {
self.fused.is_none() && self.body_of.is_none()
}
pub fn executed_children(&self) -> impl Iterator<Item = PlanNodeWire<'a>> + 'a {
self.children
.iter()
.map(plan_node_wire)
.filter(|child| child.is_executed_child())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::wire::plan_test_fixtures::{args_mut, plan_seek_wire_node, plan_wire_node};
#[test]
#[should_panic(
expected = "plan wire KernelHops is a non-negative integer when KernelRung is chain"
)]
fn a_chain_rung_without_its_hop_count_fails_the_parse() {
let mut node = plan_wire_node("Match", 0, Some(1), vec![]);
args_mut(&mut node).insert(
plan_keys::KERNEL_RUNG.to_string(),
CypherValue::Str("chain".into()),
);
let _ = plan_node_wire(&node);
}
#[test]
fn the_vector_scan_group_decodes_to_the_typed_pair() {
let mut node = plan_wire_node("Match", 0, Some(1), vec![]);
for (key, count) in plan_keys::VECTOR_SCAN_GROUP_KEYS.into_iter().zip([2, 0]) {
args_mut(&mut node).insert(key.to_string(), CypherValue::Int(count));
}
let wire = plan_node_wire(&node);
let scans = wire.metrics.expect("a PROFILE node").vector_scan;
assert_eq!((scans.matrix, scans.value_scan), (2, 0));
}
#[test]
fn a_node_without_the_vector_scan_group_decodes_to_zeros() {
let node = plan_wire_node("Match", 0, Some(1), vec![]);
let scans = plan_node_wire(&node)
.metrics
.expect("a PROFILE node")
.vector_scan;
assert_eq!((scans.matrix, scans.value_scan), (0, 0));
let [matrix, value] = plan_keys::VECTOR_SCAN_GROUP_KEYS;
assert_ne!(matrix, value);
}
#[test]
#[should_panic(expected = "are an all-or-none group")]
fn half_a_vector_scan_group_fails_the_parse() {
let mut node = plan_wire_node("Match", 0, Some(1), vec![]);
args_mut(&mut node).insert(
plan_keys::VECTOR_SCAN_MATRIX.to_string(),
CypherValue::Int(1),
);
let _ = plan_node_wire(&node);
}
#[test]
fn subtree_totals_map_the_tree() {
let expand = plan_wire_node("Expand", 3, Some(5), vec![]);
let filter = plan_wire_node("Filter", 2, Some(2), vec![expand]);
let scan = plan_wire_node("NodeByLabelScan", 1, Some(3), vec![]);
let root = plan_wire_node("ProduceResults", 0, Some(10), vec![scan, filter]);
let totals = plan_subtree_totals(&root);
assert_eq!(totals[&0], 20, "the root's total covers the pipeline");
assert_eq!(totals[&2], 7, "the filter's total heads the expand");
assert_eq!(totals[&1], 3, "a leaf's total equals its own time");
let explain = plan_subtree_totals(&plan_wire_node("ProduceResults", 0, None, vec![]));
assert_eq!(explain[&0], 0);
}
#[test]
fn the_seek_operators_ride_the_wire_form() {
let seek = plan_seek_wire_node(
"NodeIndexSeekByRange",
"RANGE INDEX n:User(age) WHERE age > 5, WHERE filter",
5,
1,
);
let point = plan_seek_wire_node(
"NodeIndexSeek",
"RANGE INDEX n:Person(name) WHERE name = 'Alice'",
1,
2,
);
let root = plan_wire_node("ProduceResults", 0, None, vec![seek, point]);
let wire = plan_node_wire(&root);
assert_eq!(wire.operator_type, "ProduceResults");
let window = plan_node_wire(&wire.children[0]);
assert_eq!(window.operator_type, "NodeIndexSeekByRange");
assert_eq!(
window.details,
"RANGE INDEX n:User(age) WHERE age > 5, WHERE filter"
);
assert_eq!(window.estimated_rows, Some(5));
let read = plan_node_wire(&wire.children[1]);
assert_eq!(read.operator_type, "NodeIndexSeek");
assert_eq!(
read.details,
"RANGE INDEX n:Person(name) WHERE name = 'Alice'"
);
assert_eq!(read.estimated_rows, Some(1));
}
}