Skip to main content

relate_model/
plan_memo.rs

1//! The expression-memo group's wire shape (ADR-0654): the typed view of
2//! the `Memo*` args a PROFILE node carries when its memos were probed, the
3//! closed vocabulary of memo types the plan root names, and the one
4//! read-side validation (all-or-none, non-negative, PROFILE-only) the other
5//! metric groups have. `plan_wire` reads the group through
6//! [`memo_group`]; the producer is `relate`'s `PlanNode::to_value`.
7
8use super::plan_args::metric_group_ints;
9use super::plan_keys;
10use crate::CypherValue;
11
12/// The memo types a plan root's `MemoKinds` can name (ADR-0654 ยง3): a
13/// closed set of stable names, the vocabulary's one spelling โ€” the
14/// executor's memo type maps onto it, never a free string.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum MemoKindWire {
17    /// The node-label guard memo of a traversal stage.
18    NodeLabel,
19    /// The `datetime(<string>)` constructor memo.
20    Datetime,
21}
22
23impl MemoKindWire {
24    /// Every kind, in vocabulary order; the bit of a kind in
25    /// [`MemoKindsWire`] is its index here.
26    pub const ALL: [MemoKindWire; 2] = [MemoKindWire::NodeLabel, MemoKindWire::Datetime];
27    /// The node-label memo's wire name.
28    pub const NODE_LABEL: &'static str = "node-label";
29    /// The datetime constructor memo's wire name.
30    pub const DATETIME: &'static str = "datetime";
31    /// Every wire name, in [`Self::ALL`] order.
32    pub const NAMES: [&'static str; 2] = [Self::NODE_LABEL, Self::DATETIME];
33
34    /// The kind's wire name.
35    pub const fn as_str(self) -> &'static str {
36        match self {
37            MemoKindWire::NodeLabel => Self::NODE_LABEL,
38            MemoKindWire::Datetime => Self::DATETIME,
39        }
40    }
41
42    const fn bit(self) -> u8 {
43        1 << self as u8
44    }
45}
46
47/// A set of [`MemoKindWire`]s, a bitset so the metric bundles stay `Copy`.
48#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
49pub struct MemoKindsWire(u8);
50
51impl MemoKindsWire {
52    /// The set with `kind` added.
53    pub const fn with(self, kind: MemoKindWire) -> Self {
54        Self(self.0 | kind.bit())
55    }
56
57    /// The union of two sets.
58    pub const fn union(self, other: Self) -> Self {
59        Self(self.0 | other.0)
60    }
61
62    /// Whether the set holds `kind`.
63    pub const fn contains(self, kind: MemoKindWire) -> bool {
64        self.0 & kind.bit() != 0
65    }
66
67    /// Whether the set holds no kind.
68    pub const fn is_empty(self) -> bool {
69        self.0 == 0
70    }
71
72    /// The members' wire names, in vocabulary order.
73    pub fn names(self) -> impl Iterator<Item = &'static str> {
74        MemoKindWire::ALL
75            .into_iter()
76            .filter(move |kind| self.contains(*kind))
77            .map(MemoKindWire::as_str)
78    }
79
80    /// The set named by `names`; `None` when a name is outside the
81    /// vocabulary.
82    pub fn from_names<'n>(names: impl IntoIterator<Item = &'n str>) -> Option<Self> {
83        names.into_iter().try_fold(Self::default(), |set, name| {
84            let kind = MemoKindWire::ALL
85                .into_iter()
86                .find(|kind| kind.as_str() == name)?;
87            Some(set.with(kind))
88        })
89    }
90}
91
92/// The expression-memo counters a PROFILE node reports (ADR-0654): the
93/// per-memo facts of ADR-0640 summed over the node's memos, plus how many
94/// of them gave up at their hit-rate review. `bytes` is the tables'
95/// allocation when read and is never part of `memory_bytes`. `kinds` is
96/// non-empty on the plan root only (constructor memos attach there).
97#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
98pub struct PlanMemoWire {
99    pub probes: i64,
100    pub hits: i64,
101    pub inserts: i64,
102    pub refused: i64,
103    pub bytes: i64,
104    pub disabled_count: i64,
105    pub kinds: MemoKindsWire,
106}
107
108/// Read one node's memo group (ADR-0654): `None` when the node carries no
109/// memo key, the typed counters when it carries the all-or-none integers of
110/// a probed memo on a PROFILE node. Anything else โ€” a partial group, a
111/// group on an EXPLAIN node, zero probes, a negative value, a kind outside
112/// [`MemoKindWire::NAMES`], kinds without the group โ€” is a wire-contract
113/// break that fails loudly.
114pub(super) fn memo_group(
115    args: &crate::IndexMap<String, CypherValue>,
116    has_metrics: bool,
117) -> Option<PlanMemoWire> {
118    let ints = metric_group_ints(args, plan_keys::MEMO_GROUP_KEYS);
119    let kinds = match args.get(plan_keys::MEMO_KINDS) {
120        None => MemoKindsWire::default(),
121        Some(CypherValue::List(names)) => {
122            let names = names.iter().map(|name| match name {
123                CypherValue::Str(name) => name.as_str(),
124                other => panic!(
125                    "plan wire {} entries are strings (ADR-0654), got {other:?}",
126                    plan_keys::MEMO_KINDS
127                ),
128            });
129            MemoKindsWire::from_names(names).unwrap_or_else(|| {
130                panic!(
131                    "plan wire {} names come from {:?} (ADR-0654)",
132                    plan_keys::MEMO_KINDS,
133                    MemoKindWire::NAMES
134                )
135            })
136        }
137        Some(other) => panic!(
138            "plan wire {} is a list of strings when present (ADR-0654), got {other:?}",
139            plan_keys::MEMO_KINDS
140        ),
141    };
142    match (has_metrics, ints) {
143        (_, None) if kinds.is_empty() => None,
144        (true, Some([probes, hits, inserts, refused, bytes, disabled_count])) if probes > 0 => {
145            Some(PlanMemoWire {
146                probes,
147                hits,
148                inserts,
149                refused,
150                bytes,
151                disabled_count,
152                kinds,
153            })
154        }
155        (has_metrics, ints) => panic!(
156            "plan wire {}..{} are non-negative integers emitted together \
157             with a positive {}, only on a PROFILE node, {} only beside \
158             them (ADR-0654), got metrics={has_metrics} ints={ints:?} \
159             kinds={kinds:?}",
160            plan_keys::MEMO_PROBES,
161            plan_keys::MEMO_DISABLED_COUNT,
162            plan_keys::MEMO_PROBES,
163            plan_keys::MEMO_KINDS
164        ),
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171    use crate::wire::plan_node_wire;
172    use crate::wire::plan_test_fixtures::{args_mut, plan_wire_node};
173
174    fn put_memo_group(node: &mut CypherValue, probes: i64, hits: i64, bytes: i64) {
175        let args = args_mut(node);
176        for (key, value) in [
177            (plan_keys::MEMO_PROBES, probes),
178            (plan_keys::MEMO_HITS, hits),
179            (plan_keys::MEMO_INSERTS, 3),
180            (plan_keys::MEMO_REFUSED, 1),
181            (plan_keys::MEMO_BYTES, bytes),
182            (plan_keys::MEMO_DISABLED_COUNT, 2),
183        ] {
184            args.insert(key.to_string(), CypherValue::Int(value));
185        }
186    }
187
188    /// ADR-0654: the memo group parses to its typed form beside the
189    /// root's kinds, and a node without it reads `None` (presence-only).
190    #[test]
191    fn the_memo_group_round_trips_and_is_absent_when_unused() {
192        let mut root = plan_wire_node("ProduceResults", 0, Some(1), vec![]);
193        assert_eq!(plan_node_wire(&root).metrics.unwrap().memo, None);
194        put_memo_group(&mut root, 100, 90, 4096);
195        args_mut(&mut root).insert(
196            plan_keys::MEMO_KINDS.to_string(),
197            CypherValue::List(vec![
198                CypherValue::Str("node-label".into()),
199                CypherValue::Str("datetime".into()),
200            ]),
201        );
202        let memo = plan_node_wire(&root).metrics.unwrap().memo.unwrap();
203        assert_eq!(
204            (memo.probes, memo.hits, memo.inserts, memo.refused),
205            (100, 90, 3, 1)
206        );
207        assert_eq!((memo.bytes, memo.disabled_count), (4096, 2));
208        assert_eq!(
209            memo.kinds.names().collect::<Vec<_>>(),
210            MemoKindWire::NAMES.to_vec()
211        );
212    }
213
214    #[test]
215    #[should_panic(expected = "are an all-or-none group")]
216    fn a_partial_memo_group_fails_the_parse() {
217        let mut node = plan_wire_node("Match", 0, Some(1), vec![]);
218        args_mut(&mut node).insert(plan_keys::MEMO_PROBES.to_string(), CypherValue::Int(5));
219        let _ = plan_node_wire(&node);
220    }
221
222    #[test]
223    #[should_panic(expected = "only on a PROFILE node")]
224    fn a_memo_group_on_an_explain_node_fails_the_parse() {
225        let mut node = plan_wire_node("Match", 0, None, vec![]);
226        put_memo_group(&mut node, 5, 1, 8);
227        let _ = plan_node_wire(&node);
228    }
229
230    #[test]
231    #[should_panic(expected = "only on a PROFILE node")]
232    fn a_zero_probe_memo_group_fails_the_parse() {
233        let mut node = plan_wire_node("Match", 0, Some(1), vec![]);
234        put_memo_group(&mut node, 0, 0, 0);
235        let _ = plan_node_wire(&node);
236    }
237
238    #[test]
239    #[should_panic(expected = "names come from")]
240    fn an_unknown_memo_kind_fails_the_parse() {
241        let mut node = plan_wire_node("Match", 0, Some(1), vec![]);
242        put_memo_group(&mut node, 5, 1, 8);
243        args_mut(&mut node).insert(
244            plan_keys::MEMO_KINDS.to_string(),
245            CypherValue::List(vec![CypherValue::Str("bogus".into())]),
246        );
247        let _ = plan_node_wire(&node);
248    }
249}