Skip to main content

relate_executor/exec/
bulk.rs

1//! Batched execution of global bulk writes (ADR-0209, LABS-263).
2//!
3//! A statement like `MATCH (n) DETACH DELETE n` or
4//! `MATCH (n) MATCH (m) WITH n AS a, m AS b CREATE (a)-[:TAGGED]->(b)`
5//! has no selective anchor: it touches every matched entity, and running
6//! it as one giant transaction materializes the whole redo in a single
7//! scratch and lands it as a single WAL record (which can cross the
8//! 64 MiB payload limit or exhaust memory). This module detects those
9//! shapes at plan time — conservatively, only when per-row effects are
10//! independent of batch boundaries — and provides the pieces the
11//! auto-commit path (`relate::commit`) needs to run them in bounded
12//! batches, one WAL commit per batch:
13//!
14//! - [`analyze_bulk_write`] — plan-shape detection (this file);
15//! - [`BulkWrite::collect_targets`] — phase 1: snapshot the matched
16//!   entity id space (memory O(entities), never O(cross product));
17//! - [`BulkWrite::execute_chunk`] — phase 2: apply up to `budget` work
18//!   units starting at `cursor`, on the caller's scratch.
19//!
20//! The two phases live in [`run`]; this file holds the plan analysis.
21//!
22//! Semantics: the matched set is fixed before the first batch writes,
23//! and every eligible write's per-row effect is independent of when
24//! sibling rows ran, so the final state and the summed write statistics
25//! equal the unbatched run. On the error path earlier batches stay
26//! committed — the documented `CALL { } IN TRANSACTIONS` trade-off. One
27//! error is preflighted before the first commit: a non-`DETACH` node
28//! `DELETE`'s `DeleteConnectedNode` check. That keeps the statement
29//! atomic for this error only as long as no concurrent writer adds a
30//! relationship after the preflight snapshot; such a race surfaces as a
31//! mid-run error with earlier batches committed, like any other
32//! mid-statement failure.
33
34use std::collections::HashSet;
35
36use relate_ir::{Clause, Expr, PathPattern, RemoveItem, SetItem};
37use relate_names::SmallName;
38
39use crate::graph::Graph;
40use relate_planner::LogicalPlan;
41
42use super::label_expr_ok;
43
44mod run;
45
46pub use run::{BulkCursor, BulkTargets};
47
48#[cfg(test)]
49mod tests;
50
51/// Default work estimate at or above which an eligible statement is
52/// batched instead of running as one transaction.
53pub const DEFAULT_BATCH_THRESHOLD: u64 = 10_000;
54/// Default per-batch work budget (estimated touched entities).
55pub const DEFAULT_BATCH_BUDGET: u64 = 25_000;
56
57/// One matched variable's identity source: a bare node pattern
58/// `(<var> [:labels…])` or a bare relationship pattern
59/// `()-[<var> [:types…]]->()`.
60#[derive(Debug, Clone)]
61pub(super) enum FactorSource {
62    Nodes { labels: Vec<String> },
63    Rels { types: Vec<String> },
64}
65
66/// A matched variable and where its entities come from.
67#[derive(Debug, Clone)]
68pub(super) struct Factor {
69    var: String,
70    source: FactorSource,
71}
72
73/// The write clause of an eligible statement, plus what it may
74/// reference: one variant per write flavor, carrying the payload the
75/// execution arm needs so execution matches one enum exactly once.
76#[derive(Debug, Clone)]
77pub(super) enum BulkKind {
78    Delete {
79        detach: bool,
80        /// The variables the `DELETE` names; factors not named keep
81        /// their entities.
82        targets: HashSet<String>,
83    },
84    Set {
85        items: Vec<SetItem>,
86    },
87    Remove {
88        items: Vec<RemoveItem>,
89    },
90    Create {
91        patterns: Vec<PathPattern>,
92    },
93}
94
95/// A plan-time eligible global bulk write (ADR-0209 §1).
96#[derive(Debug, Clone)]
97pub struct BulkWrite {
98    pub(super) kind: BulkKind,
99    pub(super) factors: Vec<Factor>,
100}
101
102/// Whether `pattern` is a bare node pattern `(<var> [:labels…])`: named,
103/// no relationship, no properties, no predicates anywhere, no label
104/// expression, no path variable, no GPM-only features.
105fn bare_node_factor(pattern: &PathPattern) -> Option<Factor> {
106    if pattern.has_path_name()
107        || !pattern.rels.is_empty()
108        || pattern.nodes.len() != 1
109        || pattern.needs_gpm()
110    {
111        return None;
112    }
113    let node = &pattern.nodes[0];
114    if !label_expr_ok(&node.label_expr, &node.labels)
115        || node.properties.is_some()
116        || node.where_clause.is_some()
117    {
118        return None;
119    }
120    Some(Factor {
121        // Text render: the bulk factor's label/type lists feed the
122        // store's count APIs (String domain).
123        var: node.variable.as_ref()?.to_string(),
124        source: FactorSource::Nodes {
125            labels: node.label_names().map(|label| label.to_string()).collect(),
126        },
127    })
128}
129
130/// Whether `pattern` is a bare relationship pattern
131/// `()-[<var> [:types…]]->()`: both endpoints anonymous and bare, the
132/// relationship named, fixed length, no properties or predicates.
133fn bare_rel_factor(pattern: &PathPattern) -> Option<Factor> {
134    if pattern.has_path_name()
135        || pattern.nodes.len() != 2
136        || pattern.rels.len() != 1
137        || pattern.needs_gpm()
138    {
139        return None;
140    }
141    for node in &pattern.nodes {
142        if node.variable.is_some()
143            || !node.labels.is_empty()
144            || node.label_expr.is_some()
145            || node.properties.is_some()
146            || node.where_clause.is_some()
147        {
148            return None;
149        }
150    }
151    let rel = &pattern.rels[0];
152    if rel.var_length
153        || rel.quantified
154        || !label_expr_ok(&rel.type_expr, &rel.types)
155        || rel.properties.is_some()
156        || rel.where_clause.is_some()
157    {
158        return None;
159    }
160    Some(Factor {
161        var: rel.variable.as_ref()?.to_string(),
162        source: FactorSource::Rels {
163            types: rel.type_names().map(|ty| ty.to_string()).collect(),
164        },
165    })
166}
167
168/// The variable a `SET`/`REMOVE` target expression roots at:
169/// `n`, `n.k`, or `n[k]` with `n` a plain variable.
170fn target_root_var(expr: &Expr) -> Option<&SmallName> {
171    match expr {
172        Expr::Variable(name) => Some(name),
173        Expr::Property { expr, .. } | Expr::DynamicProperty { expr, .. } => match expr.as_ref() {
174            Expr::Variable(name) => Some(name),
175            _ => None,
176        },
177        _ => None,
178    }
179}
180
181/// The variables `expr` references, via the IR walker.
182fn referenced_vars(expr: &Expr) -> HashSet<String> {
183    let mut out = HashSet::new();
184    relate_ir::expr_vars(expr, &mut out);
185    out
186}
187
188/// `expr` references no variable outside `allowed`.
189fn refs_within(expr: &Expr, allowed: &HashSet<String>) -> bool {
190    referenced_vars(expr).is_subset(allowed)
191}
192
193/// Shared per-item eligibility rule for `SET`/`REMOVE`: every target
194/// roots at a matched variable, and every value/dynamic-key expression
195/// references at most that same variable (per-row effects then cannot
196/// depend on when sibling rows ran — ADR-0209 §1). Each item arrives as
197/// its target expression plus the value/dynamic-key expressions to
198/// scope-check.
199fn per_item_eligible<'a>(
200    items: impl IntoIterator<Item = (&'a Expr, Vec<&'a Expr>)>,
201    scope: &HashSet<String>,
202) -> bool {
203    items.into_iter().all(|(target, value_exprs)| {
204        let Some(root) = target_root_var(target) else {
205            return false;
206        };
207        if !root.with_str(|text| scope.contains(text)) {
208            return false;
209        }
210        // Text render: the allowed-set is the refs_within String domain.
211        let allowed = HashSet::from([root.to_string()]);
212        value_exprs.iter().all(|expr| refs_within(expr, &allowed))
213    })
214}
215
216/// Whether the `SET` items are batch-safe (see [`per_item_eligible`]).
217fn set_items_eligible(items: &[SetItem], scope: &HashSet<String>) -> bool {
218    !items.is_empty()
219        && per_item_eligible(
220            items.iter().map(|item| match item {
221                SetItem::Property { target, value } => {
222                    let mut exprs = vec![value];
223                    if let Expr::DynamicProperty { key, .. } = target {
224                        exprs.push(key);
225                    }
226                    (target, exprs)
227                }
228                SetItem::ReplaceAll { target, value } => (target, vec![value]),
229                SetItem::MergeMap { target, value } => (target, vec![value]),
230                SetItem::Labels { target, .. } => (target, Vec::new()),
231                SetItem::LabelsFunction { target, value, .. } => (target, vec![value]),
232            }),
233            scope,
234        )
235}
236
237/// Whether the `REMOVE` items are batch-safe (same target rule; the only
238/// expressions are dynamic property keys).
239fn remove_items_eligible(items: &[RemoveItem], scope: &HashSet<String>) -> bool {
240    !items.is_empty()
241        && per_item_eligible(
242            items.iter().map(|item| match item {
243                RemoveItem::Property { target } => {
244                    let exprs = match target {
245                        Expr::DynamicProperty { key, .. } => vec![key.as_ref()],
246                        _ => Vec::new(),
247                    };
248                    (target, exprs)
249                }
250                RemoveItem::Labels { target, .. } => (target, Vec::new()),
251            }),
252            scope,
253        )
254}
255
256/// Whether the `CREATE` patterns are batch-safe: no graph-sensitive
257/// expressions, compact (non-GPM) patterns, matched variables appear
258/// only as bare node endpoints, and property expressions reference only
259/// matched variables.
260fn create_patterns_eligible(patterns: &[PathPattern], scope: &HashSet<String>) -> bool {
261    !patterns.is_empty()
262        && !super::create::patterns_have_graph_sensitive_expr(patterns)
263        && patterns.iter().all(|pattern| {
264            if pattern.has_path_name() || pattern.needs_gpm() {
265                return false;
266            }
267            pattern.nodes.iter().all(|node| {
268                let endpoint_ok = match &node.variable {
269                    // A matched variable is a bare endpoint: no labels,
270                    // properties, or predicates of its own.
271                    Some(var) if var.with_str(|text| scope.contains(text)) => {
272                        node.labels.is_empty()
273                            && node.label_expr.is_none()
274                            && node.properties.is_none()
275                            && node.where_clause.is_none()
276                    }
277                    // A fresh (or anonymous) variable: created here.
278                    _ => {
279                        node.properties
280                            .as_ref()
281                            .is_none_or(|p| refs_within(p, scope))
282                            && label_expr_ok(&node.label_expr, &node.labels)
283                            && node.where_clause.is_none()
284                    }
285                };
286                endpoint_ok
287            }) && pattern.rels.iter().all(|rel| {
288                !rel.var_length
289                    && !rel.quantified
290                    && label_expr_ok(&rel.type_expr, &rel.types)
291                    && rel.where_clause.is_none()
292                    && rel
293                        .properties
294                        .as_ref()
295                        .is_none_or(|p| refs_within(p, scope))
296            })
297        })
298}
299
300/// Whether the `DELETE` clause is batch-safe, and its kind when it is:
301/// every expression must be a plain variable naming a matched factor
302/// (one walk collects the named factors and classifies their sources),
303/// and — unless `DETACH` — the targets may not mix nodes and
304/// relationships: the connectedness preflight would have to ignore the
305/// statement's own relationship targets, so that shape stays on the
306/// unbatched path.
307fn delete_kind(detach: bool, expressions: &[Expr], factors: &[Factor]) -> Option<BulkKind> {
308    if expressions.is_empty() {
309        return None;
310    }
311    let mut named = HashSet::with_capacity(expressions.len());
312    let mut touches_nodes = false;
313    let mut touches_rels = false;
314    for expr in expressions {
315        let Expr::Variable(name) = expr else {
316            return None;
317        };
318        let factor = factors.iter().find(|f| name == f.var.as_str())?;
319        match factor.source {
320            FactorSource::Nodes { .. } => touches_nodes = true,
321            FactorSource::Rels { .. } => touches_rels = true,
322        }
323        named.insert(name.to_string());
324    }
325    if !detach && touches_nodes && touches_rels {
326        return None;
327    }
328    Some(BulkKind::Delete {
329        detach,
330        targets: named,
331    })
332}
333
334/// A pure-rename `WITH` clause: whether it carries `*`, plus the
335/// old → new name pair of each explicit variable item.
336struct RenameProjection {
337    star: bool,
338    renames: Vec<(String, String)>,
339}
340
341/// Whether a `WITH` clause is a pure rename projection: no aggregation,
342/// distinct, ordering, paging, or filter, and every item a variable or
343/// `*`. `None` when the clause is not a pure rename.
344fn with_rename_projection(clause: &Clause) -> Option<RenameProjection> {
345    let Clause::With {
346        distinct,
347        group_by,
348        items,
349        order,
350        skip,
351        limit,
352        where_clause,
353        ..
354    } = clause
355    else {
356        return None;
357    };
358    if *distinct
359        || group_by.is_some()
360        || !order.is_empty()
361        || skip.is_some()
362        || limit.is_some()
363        || where_clause.is_some()
364    {
365        return None;
366    }
367    let mut star = false;
368    let mut renames = Vec::new();
369    for item in items {
370        match &item.expr {
371            Expr::Star => star = true,
372            Expr::Variable(name) => {
373                // Text render: the rename list is the projection's
374                // String column domain.
375                renames.push((
376                    name.to_string(),
377                    item.alias
378                        .as_ref()
379                        .map(|alias| alias.to_string())
380                        .unwrap_or_else(|| name.to_string()),
381                ));
382            }
383            _ => return None,
384        }
385    }
386    Some(RenameProjection { star, renames })
387}
388
389/// Apply one pure-rename `WITH` to the surviving factors, following the
390/// clause's simultaneous-assignment semantics: every item reads the
391/// incoming scope, so each factor's name is rewritten by at most one
392/// item (its first match), and a factor no item mentions survives only
393/// under `*`. Returns `None` when the projection would make the scope
394/// ambiguous for batched targeting: `*` mixed with a real rename binds
395/// two names to one entity, and an alias colliding with another
396/// surviving factor's name shadows it.
397fn apply_rename_projection(factors: &mut Vec<Factor>, projection: &RenameProjection) -> Option<()> {
398    if projection.star && projection.renames.iter().any(|(old, new)| old != new) {
399        return None;
400    }
401    let mut kept = Vec::with_capacity(factors.len());
402    for mut factor in factors.drain(..) {
403        match projection
404            .renames
405            .iter()
406            .find(|(old, _)| *old == factor.var)
407        {
408            Some((_, new)) => factor.var = new.clone(),
409            None if projection.star => {}
410            None => continue,
411        }
412        kept.push(factor);
413    }
414    *factors = kept;
415    let names: HashSet<&str> = factors.iter().map(|f| f.var.as_str()).collect();
416    (names.len() == factors.len()).then_some(())
417}
418
419/// Plan-time detection of a batchable global bulk write (ADR-0209 §1).
420///
421/// Conservative by construction: any deviation from the recognized
422/// shapes — a `WHERE`, an aggregating `WITH`, a graph-sensitive `CREATE`
423/// expression, a `RETURN` after the write, multiple parts, `UNION`,
424/// `NEXT` — yields `None` and the statement runs unbatched.
425impl BulkWrite {
426    /// An O(1) upper bound on the touched-entity count, from the label
427    /// index (plan-time counts, ADR-0218): product of per-factor upper
428    /// bounds for row writes, sum over the named factors for a delete.
429    /// `None` when a factor has no cheap bound (unlabeled rels) — the
430    /// caller then pays the real collection. Overestimates are safe
431    /// (the cost is collecting anyway); underestimates would wrongly
432    /// skip batching, so every arm errs upward.
433    pub fn estimate_upper_bound(&self, graph: &Graph) -> Option<u64> {
434        let factor_bound = |f: &Factor| -> Option<u64> {
435            match &f.source {
436                FactorSource::Nodes { labels } if !labels.is_empty() => {
437                    // intersection ≤ smallest label count
438                    labels.iter().map(|l| graph.label_count(l)).min()
439                }
440                FactorSource::Nodes { .. } => Some(graph.live_node_count() as u64),
441                // no cheap rel-type count index: decline to estimate
442                FactorSource::Rels { .. } => None,
443            }
444        };
445        match &self.kind {
446            // detach work is entities + their incident rels (1 + degree per
447            // node) — label counts give no cheap bound, so decline and let
448            // phase 1's exact total_work() decide.
449            BulkKind::Delete { detach: true, .. } => None,
450            BulkKind::Delete { targets, .. } => self
451                .factors
452                .iter()
453                .filter(|f| targets.contains(&f.var))
454                .try_fold(0u64, |acc, f| {
455                    factor_bound(f).map(|b| acc.saturating_add(b))
456                }),
457            BulkKind::Set { .. } | BulkKind::Remove { .. } | BulkKind::Create { .. } => {
458                self.factors.iter().try_fold(1u64, |acc, f| {
459                    factor_bound(f).map(|b| acc.saturating_mul(b))
460                })
461            }
462        }
463    }
464}
465
466pub fn analyze_bulk_write(plan: &LogicalPlan) -> Option<BulkWrite> {
467    if plan.parts.len() != 1 || !plan.union_all.is_empty() || plan.next.is_some() {
468        return None;
469    }
470    let clauses = &plan.parts[0];
471    let mut factors: Vec<Factor> = Vec::new();
472    let mut i = 0;
473    while let Some(Clause::Match {
474        optional,
475        patterns,
476        where_clause,
477        search,
478        ..
479    }) = clauses.get(i)
480    {
481        if *optional || where_clause.is_some() || search.is_some() || patterns.is_empty() {
482            return None;
483        }
484        for pattern in patterns {
485            factors.push(bare_node_factor(pattern).or_else(|| bare_rel_factor(pattern))?);
486        }
487        i += 1;
488    }
489    if factors.is_empty() {
490        return None;
491    }
492    // A repeated variable across patterns is a self-join in the
493    // unbatched engine, not a cross product of independent factors.
494    if factors.iter().map(|f| &f.var).collect::<HashSet<_>>().len() != factors.len() {
495        return None;
496    }
497    // Pure-rename WITHs only; the write clause references the final names.
498    while let Some(clause @ Clause::With { .. }) = clauses.get(i) {
499        let projection = with_rename_projection(clause)?;
500        apply_rename_projection(&mut factors, &projection)?;
501        i += 1;
502    }
503    // Exactly one terminal write clause; nothing may follow it.
504    if i + 1 != clauses.len() {
505        return None;
506    }
507    let scope: HashSet<String> = factors.iter().map(|f| f.var.clone()).collect();
508    let kind = match &clauses[i] {
509        Clause::Delete {
510            detach,
511            expressions,
512        } => delete_kind(*detach, expressions, &factors)?,
513        Clause::Set { items } if set_items_eligible(items, &scope) => BulkKind::Set {
514            items: items.clone(),
515        },
516        Clause::Remove { items } if remove_items_eligible(items, &scope) => BulkKind::Remove {
517            items: items.clone(),
518        },
519        Clause::Create { patterns } if create_patterns_eligible(patterns, &scope) => {
520            BulkKind::Create {
521                patterns: patterns.clone(),
522            }
523        }
524        _ => return None,
525    };
526    Some(BulkWrite { kind, factors })
527}