use super::plan_keys;
use super::plan_warning::PlanWarning;
use crate::CypherValue;
pub const PLAN_UNAVAILABLE: &str = "-";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KernelRungWire {
Chain { hops: i64 },
HubStar,
FrontierNfa,
Walker,
}
impl KernelRungWire {
pub const CHAIN: &'static str = "chain";
pub const HUB_STAR: &'static str = "hub-star";
pub const FRONTIER_NFA: &'static str = "frontier-nfa";
pub const WALKER: &'static str = "walker";
pub const NAMES: [&'static str; 4] = [
Self::CHAIN,
Self::HUB_STAR,
Self::FRONTIER_NFA,
Self::WALKER,
];
pub const fn as_str(self) -> &'static str {
match self {
KernelRungWire::Chain { .. } => Self::CHAIN,
KernelRungWire::HubStar => Self::HUB_STAR,
KernelRungWire::FrontierNfa => Self::FRONTIER_NFA,
KernelRungWire::Walker => Self::WALKER,
}
}
pub const fn hops(self) -> Option<i64> {
match self {
KernelRungWire::Chain { hops } => Some(hops),
KernelRungWire::HubStar | KernelRungWire::FrontierNfa | KernelRungWire::Walker => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PlanMetricsWire {
pub rows: i64,
pub time_ns: i64,
pub db_hits: i64,
pub memory_bytes: i64,
pub expression_built_bytes: i64,
pub reads: PlanReadsWire,
pub phases: PlanPhasesWire,
pub start: Option<PlanStartWire>,
pub kernel: Option<KernelRungWire>,
pub batched: bool,
pub zone_skips: i64,
pub frontier: PlanFrontierWire,
pub frontier_decline: Option<&'static str>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct PlanFrontierWire {
pub edge_visits: i64,
pub levels: i64,
pub endpoints: i64,
pub cells: i64,
pub memo_hits: i64,
pub memo_misses: i64,
pub representative_proofs: i64,
pub search_proven: i64,
pub search_disproven: i64,
pub declined_exhausted: i64,
pub budget_fraction: f64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PlanProfiledFacts {
pub metrics: PlanMetricsWire,
pub total_time_ns: i64,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PlanReadsWire {
pub hops: i64,
pub neighbor_walks: i64,
pub node_reads: i64,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PlanPhasesWire {
pub seek_ns: i64,
pub walk_ns: i64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PlanStartWire {
pub element: i64,
pub backward: bool,
pub reason: &'static str,
}
pub struct PlanNodeWire<'a> {
pub operator_type: &'a str,
pub id: i64,
pub details: &'a str,
pub estimated_rows: Option<i64>,
pub metrics: Option<PlanMetricsWire>,
pub args: &'a crate::IndexMap<String, CypherValue>,
pub identifiers: Vec<&'a str>,
pub children: &'a [CypherValue],
pub warnings: Vec<PlanWarning>,
}
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";
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 scalars = metric_group_ints(
args,
&[
plan_keys::ROWS,
plan_keys::TIME_NS,
plan_keys::DB_HITS,
plan_keys::MEMORY_BYTES,
plan_keys::EXPRESSION_BUILT_BYTES,
],
);
let has_metrics = scalars.is_some();
let phases = metric_set_ints(
args,
&[plan_keys::SEEK_TIME_NS, plan_keys::WALK_TIME_NS],
has_metrics,
)
.map(|values| PlanPhasesWire {
seek_ns: values[0],
walk_ns: values[1],
})
.unwrap_or_default();
let reads = metric_set_ints(
args,
&[
plan_keys::HOPS,
plan_keys::NEIGHBOR_WALKS,
plan_keys::NODE_READS,
],
has_metrics,
)
.map(|values| PlanReadsWire {
hops: values[0],
neighbor_walks: values[1],
node_reads: values[2],
})
.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)) if element >= 0 => {
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) if hops >= 0 => 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::HUB_STAR => payload_free(KernelRungWire::HubStar),
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)) if skips >= 0 => 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 frontier = {
let ints = metric_group_ints(
args,
&[
plan_keys::FRONTIER_EDGES,
plan_keys::FRONTIER_LEVELS,
plan_keys::FRONTIER_ENDPOINTS,
plan_keys::FRONTIER_CELLS,
plan_keys::FRONTIER_MEMO_HITS,
plan_keys::FRONTIER_MEMO_MISSES,
plan_keys::FRONTIER_REPRESENTATIVE_PROOFS,
plan_keys::FRONTIER_SEARCH_PROVEN,
plan_keys::FRONTIER_SEARCH_DISPROVEN,
plan_keys::FRONTIER_DECLINED_EXHAUSTED,
],
);
let fraction = optional_fraction(args, plan_keys::FRONTIER_BUDGET_FRACTION);
match (has_metrics, ints, fraction) {
(_, None, None) => PlanFrontierWire::default(),
(true, Some(values), Some(fraction)) => PlanFrontierWire {
edge_visits: values[0],
levels: values[1],
endpoints: values[2],
cells: values[3],
memo_hits: values[4],
memo_misses: values[5],
representative_proofs: values[6],
search_proven: values[7],
search_disproven: values[8],
declined_exhausted: values[9],
budget_fraction: 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 metrics = scalars.map(|values| PlanMetricsWire {
rows: values[0],
time_ns: values[1],
db_hits: values[2],
memory_bytes: values[3],
expression_built_bytes: values[4],
reads,
phases,
start,
kernel,
batched,
zone_skips,
frontier,
frontier_decline,
});
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,
metrics,
args,
identifiers,
children,
warnings,
}
}
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}")),
}
}
fn metric_set_ints(
args: &crate::IndexMap<String, CypherValue>,
keys: &[&str],
has_metrics: bool,
) -> Option<Vec<i64>> {
match (has_metrics, metric_group_ints(args, keys)) {
(false, None) => None,
(true, Some(values)) => Some(values),
(false, Some(_)) => panic!(
"plan wire {keys:?} are present without the metric fields \
(all-or-none group policy)"
),
(true, None) => panic!(
"plan wire {keys:?} are absent from the metric fields \
(all-or-none group policy)"
),
}
}
fn metric_group_ints(
args: &crate::IndexMap<String, CypherValue>,
keys: &[&str],
) -> Option<Vec<i64>> {
let values: Vec<Option<i64>> = keys.iter().map(|k| optional_int(args, k)).collect();
let any_present = values.iter().any(Option::is_some);
let all_present = values.iter().all(Option::is_some);
match (any_present, all_present) {
(false, _) => None,
(true, false) => panic!(
"plan wire {keys:?} are an all-or-none group, got a partial group: \
values={values:?}"
),
(true, true) => {
if let Some((key, value)) = keys
.iter()
.zip(&values)
.find_map(|(key, value)| value.filter(|n| *n < 0).map(|n| (*key, n)))
{
panic!(
"plan wire {key} is non-negative when present, got {value} \
(all-or-none non-negative group)"
);
}
Some(
values
.into_iter()
.map(|v| v.expect("the group is all-present"))
.collect(),
)
}
}
}
impl PlanNodeWire<'_> {
pub fn input_rows(&self) -> Option<u64> {
self.children
.first()
.and_then(|first| plan_node_wire(first).metrics.map(|m| metric_u64(m.rows)))
}
}
fn optional_int(args: &crate::IndexMap<String, CypherValue>, key: &str) -> Option<i64> {
match args.get(key) {
None => None,
Some(CypherValue::Int(n)) => Some(*n),
other => panic!("plan wire {key} is an integer when present (ADR-0345), got {other:?}"),
}
}
fn optional_bool(args: &crate::IndexMap<String, CypherValue>, key: &str) -> Option<bool> {
match args.get(key) {
None => None,
Some(CypherValue::Bool(flag)) => Some(*flag),
other => panic!("plan wire {key} is a boolean when present (LABS-369), got {other:?}"),
}
}
fn optional_fraction(args: &crate::IndexMap<String, CypherValue>, key: &str) -> Option<f64> {
match args.get(key) {
None => None,
Some(CypherValue::Float(fraction)) if *fraction >= 0.0 => Some(*fraction),
other => {
panic!("plan wire {key} is a non-negative float when present (ADR-0516), got {other:?}")
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::wire::plan_test_fixtures::{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![]);
let CypherValue::Map(entries) = &mut node else {
unreachable!("the fixture builds a map")
};
let Some(CypherValue::Map(args)) = entries.get_mut(plan_keys::ARGS) else {
unreachable!("the fixture builds an args map")
};
args.insert(
plan_keys::KERNEL_RUNG.to_string(),
CypherValue::Str("chain".into()),
);
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));
}
}