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    pub(super) cypher_version: Option<u32>,
101}
102
103/// Whether `pattern` is a bare node pattern `(<var> [:labels…])`: named,
104/// no relationship, no properties, no predicates anywhere, no label
105/// expression, no path variable, no GPM-only features.
106fn bare_node_factor(pattern: &PathPattern) -> Option<Factor> {
107    if pattern.has_path_name()
108        || !pattern.rels.is_empty()
109        || pattern.nodes.len() != 1
110        || pattern.needs_gpm()
111    {
112        return None;
113    }
114    let node = &pattern.nodes[0];
115    if !label_expr_ok(&node.label_expr, &node.labels)
116        || node.properties.is_some()
117        || node.where_clause.is_some()
118    {
119        return None;
120    }
121    Some(Factor {
122        // Text render: the bulk factor's label/type lists feed the
123        // store's count APIs (String domain).
124        var: node.variable.as_ref()?.to_string(),
125        source: FactorSource::Nodes {
126            labels: node.label_names().map(|label| label.to_string()).collect(),
127        },
128    })
129}
130
131/// Whether `pattern` is a bare relationship pattern
132/// `()-[<var> [:types…]]->()`: both endpoints anonymous and bare, the
133/// relationship named, fixed length, no properties or predicates.
134fn bare_rel_factor(pattern: &PathPattern) -> Option<Factor> {
135    if pattern.has_path_name()
136        || pattern.nodes.len() != 2
137        || pattern.rels.len() != 1
138        || pattern.needs_gpm()
139    {
140        return None;
141    }
142    for node in &pattern.nodes {
143        if node.variable.is_some()
144            || !node.labels.is_empty()
145            || node.label_expr.is_some()
146            || node.properties.is_some()
147            || node.where_clause.is_some()
148        {
149            return None;
150        }
151    }
152    let rel = &pattern.rels[0];
153    if rel.var_length
154        || rel.quantified
155        || !label_expr_ok(&rel.type_expr, &rel.types)
156        || rel.properties.is_some()
157        || rel.where_clause.is_some()
158    {
159        return None;
160    }
161    Some(Factor {
162        var: rel.variable.as_ref()?.to_string(),
163        source: FactorSource::Rels {
164            types: rel.type_names().map(|ty| ty.to_string()).collect(),
165        },
166    })
167}
168
169/// The variable a `SET`/`REMOVE` target expression roots at:
170/// `n`, `n.k`, or `n[k]` with `n` a plain variable.
171fn target_root_var(expr: &Expr) -> Option<&SmallName> {
172    match expr {
173        Expr::Variable(name) => Some(name),
174        Expr::Property { expr, .. } | Expr::DynamicProperty { expr, .. } => match expr.as_ref() {
175            Expr::Variable(name) => Some(name),
176            _ => None,
177        },
178        _ => None,
179    }
180}
181
182/// The variables `expr` references, via the IR walker.
183fn referenced_vars(expr: &Expr) -> HashSet<String> {
184    let mut out = HashSet::new();
185    relate_ir::expr_vars(expr, &mut out);
186    out
187}
188
189/// `expr` references no variable outside `allowed`.
190fn refs_within(expr: &Expr, allowed: &HashSet<String>) -> bool {
191    referenced_vars(expr).is_subset(allowed)
192}
193
194/// Shared per-item eligibility rule for `SET`/`REMOVE`: every target
195/// roots at a matched variable, and every value/dynamic-key expression
196/// references at most that same variable (per-row effects then cannot
197/// depend on when sibling rows ran — ADR-0209 §1). Each item arrives as
198/// its target expression plus the value/dynamic-key expressions to
199/// scope-check.
200fn per_item_eligible<'a>(
201    items: impl IntoIterator<Item = (&'a Expr, Vec<&'a Expr>)>,
202    scope: &HashSet<String>,
203) -> bool {
204    items.into_iter().all(|(target, value_exprs)| {
205        let Some(root) = target_root_var(target) else {
206            return false;
207        };
208        if !root.with_str(|text| scope.contains(text)) {
209            return false;
210        }
211        // Text render: the allowed-set is the refs_within String domain.
212        let allowed = HashSet::from([root.to_string()]);
213        value_exprs.iter().all(|expr| refs_within(expr, &allowed))
214    })
215}
216
217/// Whether the `SET` items are batch-safe (see [`per_item_eligible`]).
218fn set_items_eligible(items: &[SetItem], scope: &HashSet<String>) -> bool {
219    !items.is_empty()
220        && per_item_eligible(
221            items.iter().map(|item| match item {
222                SetItem::Property { target, value } => {
223                    let mut exprs = vec![value];
224                    if let Expr::DynamicProperty { key, .. } = target {
225                        exprs.push(key);
226                    }
227                    (target, exprs)
228                }
229                SetItem::ReplaceAll { target, value } => (target, vec![value]),
230                SetItem::MergeMap { target, value } => (target, vec![value]),
231                SetItem::Labels { target, .. } => (target, Vec::new()),
232                SetItem::LabelsFunction { target, value, .. } => (target, vec![value]),
233            }),
234            scope,
235        )
236}
237
238/// Whether the `REMOVE` items are batch-safe (same target rule; the only
239/// expressions are dynamic property keys).
240fn remove_items_eligible(items: &[RemoveItem], scope: &HashSet<String>) -> bool {
241    !items.is_empty()
242        && per_item_eligible(
243            items.iter().map(|item| match item {
244                RemoveItem::Property { target } => {
245                    let exprs = match target {
246                        Expr::DynamicProperty { key, .. } => vec![key.as_ref()],
247                        _ => Vec::new(),
248                    };
249                    (target, exprs)
250                }
251                RemoveItem::Labels { target, .. } => (target, Vec::new()),
252            }),
253            scope,
254        )
255}
256
257/// Whether the `CREATE` patterns are batch-safe: no graph-sensitive
258/// expressions, compact (non-GPM) patterns, matched variables appear
259/// only as bare node endpoints, and property expressions reference only
260/// matched variables.
261fn create_patterns_eligible(patterns: &[PathPattern], scope: &HashSet<String>) -> bool {
262    !patterns.is_empty()
263        && !super::create::patterns_have_graph_sensitive_expr(patterns)
264        && patterns.iter().all(|pattern| {
265            if pattern.has_path_name() || pattern.needs_gpm() {
266                return false;
267            }
268            pattern.nodes.iter().all(|node| {
269                let endpoint_ok = match &node.variable {
270                    // A matched variable is a bare endpoint: no labels,
271                    // properties, or predicates of its own.
272                    Some(var) if var.with_str(|text| scope.contains(text)) => {
273                        node.labels.is_empty()
274                            && node.label_expr.is_none()
275                            && node.properties.is_none()
276                            && node.where_clause.is_none()
277                    }
278                    // A fresh (or anonymous) variable: created here.
279                    _ => {
280                        node.properties
281                            .as_ref()
282                            .is_none_or(|p| refs_within(p, scope))
283                            && label_expr_ok(&node.label_expr, &node.labels)
284                            && node.where_clause.is_none()
285                    }
286                };
287                endpoint_ok
288            }) && pattern.rels.iter().all(|rel| {
289                !rel.var_length
290                    && !rel.quantified
291                    && label_expr_ok(&rel.type_expr, &rel.types)
292                    && rel.where_clause.is_none()
293                    && rel
294                        .properties
295                        .as_ref()
296                        .is_none_or(|p| refs_within(p, scope))
297            })
298        })
299}
300
301/// Whether the `DELETE` clause is batch-safe, and its kind when it is:
302/// every expression must be a plain variable naming a matched factor
303/// (one walk collects the named factors and classifies their sources),
304/// and — unless `DETACH` — the targets may not mix nodes and
305/// relationships: the connectedness preflight would have to ignore the
306/// statement's own relationship targets, so that shape stays on the
307/// unbatched path.
308fn delete_kind(detach: bool, expressions: &[Expr], factors: &[Factor]) -> Option<BulkKind> {
309    if expressions.is_empty() {
310        return None;
311    }
312    let mut named = HashSet::with_capacity(expressions.len());
313    let mut touches_nodes = false;
314    let mut touches_rels = false;
315    for expr in expressions {
316        let Expr::Variable(name) = expr else {
317            return None;
318        };
319        let factor = factors.iter().find(|f| name == f.var.as_str())?;
320        match factor.source {
321            FactorSource::Nodes { .. } => touches_nodes = true,
322            FactorSource::Rels { .. } => touches_rels = true,
323        }
324        named.insert(name.to_string());
325    }
326    if !detach && touches_nodes && touches_rels {
327        return None;
328    }
329    Some(BulkKind::Delete {
330        detach,
331        targets: named,
332    })
333}
334
335/// A pure-rename `WITH` clause: whether it carries `*`, plus the
336/// old → new name pair of each explicit variable item.
337struct RenameProjection {
338    star: bool,
339    renames: Vec<(String, String)>,
340}
341
342/// Whether a `WITH` clause is a pure rename projection: no aggregation,
343/// distinct, ordering, paging, or filter, and every item a variable or
344/// `*`. `None` when the clause is not a pure rename.
345fn with_rename_projection(clause: &Clause) -> Option<RenameProjection> {
346    let Clause::With {
347        distinct,
348        group_by,
349        items,
350        order,
351        skip,
352        limit,
353        where_clause,
354        ..
355    } = clause
356    else {
357        return None;
358    };
359    if *distinct
360        || group_by.is_some()
361        || !order.is_empty()
362        || skip.is_some()
363        || limit.is_some()
364        || where_clause.is_some()
365    {
366        return None;
367    }
368    let mut star = false;
369    let mut renames = Vec::new();
370    for item in items {
371        match &item.expr {
372            Expr::Star => star = true,
373            Expr::Variable(name) => {
374                // Text render: the rename list is the projection's
375                // String column domain.
376                renames.push((
377                    name.to_string(),
378                    item.alias
379                        .as_ref()
380                        .map(|alias| alias.to_string())
381                        .unwrap_or_else(|| name.to_string()),
382                ));
383            }
384            _ => return None,
385        }
386    }
387    Some(RenameProjection { star, renames })
388}
389
390/// Apply one pure-rename `WITH` to the surviving factors, following the
391/// clause's simultaneous-assignment semantics: every item reads the
392/// incoming scope, so each factor's name is rewritten by at most one
393/// item (its first match), and a factor no item mentions survives only
394/// under `*`. Returns `None` when the projection would make the scope
395/// ambiguous for batched targeting: `*` mixed with a real rename binds
396/// two names to one entity, and an alias colliding with another
397/// surviving factor's name shadows it.
398fn apply_rename_projection(factors: &mut Vec<Factor>, projection: &RenameProjection) -> Option<()> {
399    if projection.star && projection.renames.iter().any(|(old, new)| old != new) {
400        return None;
401    }
402    let mut kept = Vec::with_capacity(factors.len());
403    for mut factor in factors.drain(..) {
404        match projection
405            .renames
406            .iter()
407            .find(|(old, _)| *old == factor.var)
408        {
409            Some((_, new)) => factor.var = new.clone(),
410            None if projection.star => {}
411            None => continue,
412        }
413        kept.push(factor);
414    }
415    *factors = kept;
416    let names: HashSet<&str> = factors.iter().map(|f| f.var.as_str()).collect();
417    (names.len() == factors.len()).then_some(())
418}
419
420/// Plan-time detection of a batchable global bulk write (ADR-0209 §1).
421///
422/// Conservative by construction: any deviation from the recognized
423/// shapes — a `WHERE`, an aggregating `WITH`, a graph-sensitive `CREATE`
424/// expression, a `RETURN` after the write, multiple parts, `UNION`,
425/// `NEXT` — yields `None` and the statement runs unbatched.
426impl BulkWrite {
427    /// An O(1) upper bound on the touched-entity count, from the label
428    /// index (plan-time counts, ADR-0218): product of per-factor upper
429    /// bounds for row writes, sum over the named factors for a delete.
430    /// `None` when a factor has no cheap bound (unlabeled rels) — the
431    /// caller then pays the real collection. Overestimates are safe
432    /// (the cost is collecting anyway); underestimates would wrongly
433    /// skip batching, so every arm errs upward.
434    pub fn estimate_upper_bound(&self, graph: &Graph) -> Option<u64> {
435        let factor_bound = |f: &Factor| -> Option<u64> {
436            match &f.source {
437                FactorSource::Nodes { labels } if !labels.is_empty() => {
438                    // intersection ≤ smallest label count
439                    labels.iter().map(|l| graph.label_count(l)).min()
440                }
441                FactorSource::Nodes { .. } => Some(graph.live_node_count() as u64),
442                // no cheap rel-type count index: decline to estimate
443                FactorSource::Rels { .. } => None,
444            }
445        };
446        match &self.kind {
447            // detach work is entities + their incident rels (1 + degree per
448            // node) — label counts give no cheap bound, so decline and let
449            // phase 1's exact total_work() decide.
450            BulkKind::Delete { detach: true, .. } => None,
451            BulkKind::Delete { targets, .. } => self
452                .factors
453                .iter()
454                .filter(|f| targets.contains(&f.var))
455                .try_fold(0u64, |acc, f| {
456                    factor_bound(f).map(|b| acc.saturating_add(b))
457                }),
458            BulkKind::Set { .. } | BulkKind::Remove { .. } | BulkKind::Create { .. } => {
459                self.factors.iter().try_fold(1u64, |acc, f| {
460                    factor_bound(f).map(|b| acc.saturating_mul(b))
461                })
462            }
463        }
464    }
465}
466
467pub fn analyze_bulk_write(plan: &LogicalPlan) -> Option<BulkWrite> {
468    if plan.parts.len() != 1 || !plan.union_all.is_empty() || plan.next.is_some() {
469        return None;
470    }
471    let clauses = &plan.parts[0];
472    let mut factors: Vec<Factor> = Vec::new();
473    let mut i = 0;
474    while let Some(Clause::Match {
475        optional,
476        patterns,
477        where_clause,
478        search,
479        ..
480    }) = clauses.get(i)
481    {
482        if *optional || where_clause.is_some() || search.is_some() || patterns.is_empty() {
483            return None;
484        }
485        for pattern in patterns {
486            factors.push(bare_node_factor(pattern).or_else(|| bare_rel_factor(pattern))?);
487        }
488        i += 1;
489    }
490    if factors.is_empty() {
491        return None;
492    }
493    // A repeated variable across patterns is a self-join in the
494    // unbatched engine, not a cross product of independent factors.
495    if factors.iter().map(|f| &f.var).collect::<HashSet<_>>().len() != factors.len() {
496        return None;
497    }
498    // Pure-rename WITHs only; the write clause references the final names.
499    while let Some(clause @ Clause::With { .. }) = clauses.get(i) {
500        let projection = with_rename_projection(clause)?;
501        apply_rename_projection(&mut factors, &projection)?;
502        i += 1;
503    }
504    // Exactly one terminal write clause; nothing may follow it.
505    if i + 1 != clauses.len() {
506        return None;
507    }
508    let scope: HashSet<String> = factors.iter().map(|f| f.var.clone()).collect();
509    let kind = match &clauses[i] {
510        Clause::Delete {
511            detach,
512            expressions,
513        } => delete_kind(*detach, expressions, &factors)?,
514        Clause::Set { items } if set_items_eligible(items, &scope) => BulkKind::Set {
515            items: items.clone(),
516        },
517        Clause::Remove { items } if remove_items_eligible(items, &scope) => BulkKind::Remove {
518            items: items.clone(),
519        },
520        Clause::Create { patterns } if create_patterns_eligible(patterns, &scope) => {
521            BulkKind::Create {
522                patterns: patterns.clone(),
523            }
524        }
525        _ => return None,
526    };
527    Some(BulkWrite {
528        kind,
529        factors,
530        cypher_version: plan.cypher_version,
531    })
532}