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::{HashMap, HashSet};
35
36use relate_ir::{Clause, Direction, Expr, PathPattern, RemoveItem, SetItem};
37use relate_names::SmallName;
38
39use crate::graph::Graph;
40use relate_planner::LogicalPlan;
41
42use super::create_admission::{
43    compact_pattern, create_patterns_eligible, node_is_bare_endpoint, refs_within,
44    rel_has_static_edge_shape,
45};
46use super::label_expr_ok;
47use super::scope::is_star_item;
48
49mod run;
50
51pub use run::{BulkCursor, BulkTargets};
52
53#[cfg(test)]
54mod tests;
55
56/// Default work estimate at or above which an eligible statement is
57/// batched instead of running as one transaction.
58pub const DEFAULT_BATCH_THRESHOLD: u64 = 10_000;
59/// Default per-batch work budget (estimated touched entities).
60pub const DEFAULT_BATCH_BUDGET: u64 = 25_000;
61
62/// One matched variable's identity source: a bare node pattern
63/// `(<var> [:labels…])` or a bare relationship pattern
64/// `()-[<var> [:types…]]->()`.
65#[derive(Debug, Clone)]
66pub(super) enum FactorSource {
67    Nodes { labels: Vec<String> },
68    Rels { types: Vec<String> },
69}
70
71/// A matched variable and where its entities come from.
72#[derive(Debug, Clone)]
73pub(super) struct Factor {
74    var: String,
75    source: FactorSource,
76}
77
78/// The write clause of an eligible statement, plus what it may
79/// reference: one variant per write flavor, carrying the payload the
80/// execution arm needs so execution matches one enum exactly once.
81#[derive(Debug, Clone)]
82pub(super) enum BulkKind {
83    Delete {
84        detach: bool,
85        /// The variables the `DELETE` names; factors not named keep
86        /// their entities.
87        targets: HashSet<String>,
88    },
89    Set {
90        items: Vec<SetItem>,
91    },
92    Remove {
93        items: Vec<RemoveItem>,
94    },
95    Create {
96        patterns: Vec<PathPattern>,
97    },
98}
99
100/// A plan-time eligible global bulk write (ADR-0209 §1).
101#[derive(Debug, Clone)]
102pub struct BulkWrite {
103    pub(super) kind: BulkKind,
104    pub(super) factors: Vec<Factor>,
105}
106
107/// Whether `pattern` is a bare node pattern `(<var> [:labels…])`: named,
108/// no relationship, no properties, no predicates anywhere, no label
109/// expression, no path variable, no GPM-only features.
110fn bare_node_factor(pattern: &PathPattern) -> Option<Factor> {
111    if !compact_pattern(pattern) || !pattern.rels.is_empty() || pattern.nodes.len() != 1 {
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 directed 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 !compact_pattern(pattern) || pattern.nodes.len() != 2 || pattern.rels.len() != 1 {
136        return None;
137    }
138    for node in &pattern.nodes {
139        // Anonymous endpoints only, each bare (no labels, properties or
140        // predicate of its own).
141        if node.variable.is_some() || !node_is_bare_endpoint(node) {
142            return None;
143        }
144    }
145    let rel = &pattern.rels[0];
146    // An undirected pattern matches every non-loop relationship once per
147    // orientation; the factor's target set holds each id once (issue 70),
148    // so the shape stays on the unbatched path. A property map would make
149    // the row's effect depend on a per-element value the factor target
150    // space does not carry.
151    if rel.direction == Direction::Both
152        || !rel_has_static_edge_shape(rel)
153        || rel.properties.is_some()
154    {
155        return None;
156    }
157    Some(Factor {
158        var: rel.variable.as_ref()?.to_string(),
159        source: FactorSource::Rels {
160            types: rel.type_names().map(|ty| ty.to_string()).collect(),
161        },
162    })
163}
164
165/// The variable a `SET`/`REMOVE` target expression roots at, for the bulk
166/// eligibility rule below: `n`, `n.k`, or `n[k]` with `n` a plain
167/// variable. Deliberately one level deep — a deeper access chain
168/// (`n[x][y]`) is not eligible here, because the bulk path's per-row
169/// effect must depend on a single matched variable. The recursive twin
170/// ([`relate_ir::root_variable`], REL8-1813) answers the different
171/// question the write-target class decision asks — "is this target
172/// variable-rooted at all" — and must not replace this test.
173fn target_root_var(expr: &Expr) -> Option<&SmallName> {
174    match expr {
175        Expr::Variable(name) => Some(name),
176        Expr::Property { expr, .. } | Expr::DynamicProperty { expr, .. } => match expr.as_ref() {
177            Expr::Variable(name) => Some(name),
178            _ => None,
179        },
180        _ => None,
181    }
182}
183
184/// Shared per-item eligibility rule for `SET`/`REMOVE`: every target
185/// roots at a matched variable, and every value/dynamic-key expression
186/// references at most that same variable (per-row effects then cannot
187/// depend on when sibling rows ran — ADR-0209 §1). Each item arrives as
188/// its target expression plus the value/dynamic-key expressions to
189/// scope-check.
190fn per_item_eligible<'a>(
191    items: impl IntoIterator<Item = (&'a Expr, Vec<&'a Expr>)>,
192    scope: &HashSet<String>,
193) -> bool {
194    items.into_iter().all(|(target, value_exprs)| {
195        let Some(root) = target_root_var(target) else {
196            return false;
197        };
198        if !root.with_str(|text| scope.contains(text)) {
199            return false;
200        }
201        // Text render: the allowed-set is the refs_within String domain.
202        let allowed = HashSet::from([root.to_string()]);
203        value_exprs.iter().all(|expr| refs_within(expr, &allowed))
204    })
205}
206
207/// Whether the `SET` items are batch-safe (see [`per_item_eligible`]).
208fn set_items_eligible(items: &[SetItem], scope: &HashSet<String>) -> bool {
209    !items.is_empty()
210        && per_item_eligible(
211            items.iter().map(|item| match item {
212                SetItem::Property { target, value } => {
213                    let mut exprs = vec![value];
214                    if let Expr::DynamicProperty { key, .. } = target {
215                        exprs.push(key);
216                    }
217                    (target, exprs)
218                }
219                SetItem::ReplaceAll { target, value } => (target, vec![value]),
220                SetItem::MergeMap { target, value } => (target, vec![value]),
221                SetItem::Labels { target, .. } => (target, Vec::new()),
222                SetItem::LabelsFunction { target, value, .. } => (target, vec![value]),
223            }),
224            scope,
225        )
226}
227
228/// Whether the `REMOVE` items are batch-safe (same target rule; the only
229/// expressions are dynamic property keys).
230fn remove_items_eligible(items: &[RemoveItem], scope: &HashSet<String>) -> bool {
231    !items.is_empty()
232        && per_item_eligible(
233            items.iter().map(|item| match item {
234                RemoveItem::Property { target } => {
235                    let exprs = match target {
236                        Expr::DynamicProperty { key, .. } => vec![key.as_ref()],
237                        _ => Vec::new(),
238                    };
239                    (target, exprs)
240                }
241                RemoveItem::Labels { target, .. } => (target, Vec::new()),
242            }),
243            scope,
244        )
245}
246
247/// The `SET` target kind — eligible when every item reads only the
248/// final scope's variables ([`set_items_eligible`]'s own contract).
249fn set_kind(items: &[SetItem], scope: &HashSet<String>) -> Option<BulkKind> {
250    set_items_eligible(items, scope).then(|| BulkKind::Set {
251        items: items.to_vec(),
252    })
253}
254
255/// The `REMOVE` target kind — eligible when every item reads only the
256/// final scope's variables ([`remove_items_eligible`]'s own contract).
257fn remove_kind(items: &[RemoveItem], scope: &HashSet<String>) -> Option<BulkKind> {
258    remove_items_eligible(items, scope).then(|| BulkKind::Remove {
259        items: items.to_vec(),
260    })
261}
262
263/// The `CREATE` target kind — eligible when every pattern's refs stay
264/// within the final scope ([`create_patterns_eligible`]'s own
265/// contract).
266fn create_kind(patterns: &[PathPattern], scope: &HashSet<String>) -> Option<BulkKind> {
267    create_patterns_eligible(patterns, scope).then(|| BulkKind::Create {
268        patterns: patterns.to_vec(),
269    })
270}
271
272/// Whether the `DELETE` clause is batch-safe, and its kind when it is:
273/// every expression must be a plain variable naming a matched factor
274/// (one walk collects the named factors and classifies their sources),
275/// and — unless `DETACH` — the targets may not mix nodes and
276/// relationships: the connectedness preflight would have to ignore the
277/// statement's own relationship targets, so that shape stays on the
278/// unbatched path.
279fn delete_kind(detach: bool, expressions: &[Expr], factors: &[Factor]) -> Option<BulkKind> {
280    if expressions.is_empty() {
281        return None;
282    }
283    let mut named = HashSet::with_capacity(expressions.len());
284    let mut touches_nodes = false;
285    let mut touches_rels = false;
286    for expr in expressions {
287        let Expr::Variable(name) = expr else {
288            return None;
289        };
290        let factor = factors.iter().find(|f| name == f.var.as_str())?;
291        match factor.source {
292            FactorSource::Nodes { .. } => touches_nodes = true,
293            FactorSource::Rels { .. } => touches_rels = true,
294        }
295        named.insert(name.to_string());
296    }
297    if !detach && touches_nodes && touches_rels {
298        return None;
299    }
300    Some(BulkKind::Delete {
301        detach,
302        targets: named,
303    })
304}
305
306/// A pure-rename `WITH` clause's shape: `*` (every factor survives, its
307/// aliases identity only — a real rename would bind two names to one
308/// entity) or the old → new map of its explicit variable items (the
309/// decoder declines a second target for one source, and two sources
310/// sharing a target — either would shadow a surviving factor).
311enum RenameProjection {
312    Star,
313    Renamed(HashMap<String, String>),
314}
315
316/// Whether a `WITH` clause is a pure rename projection: no aggregation,
317/// distinct, ordering, paging, or filter, every item a variable or `*`,
318/// and no source variable renamed twice (two names for one entity, which
319/// the one-entry-per-variable factor list cannot carry). `None` when the
320/// clause is not a pure rename.
321fn with_rename_projection(clause: &Clause) -> Option<RenameProjection> {
322    let Clause::With {
323        distinct,
324        group_by,
325        items,
326        order,
327        skip,
328        limit,
329        where_clause,
330        ..
331    } = clause
332    else {
333        return None;
334    };
335    if *distinct
336        || group_by.is_some()
337        || !order.is_empty()
338        || skip.is_some()
339        || limit.is_some()
340        || where_clause.is_some()
341    {
342        return None;
343    }
344    let mut star = false;
345    let mut renames = HashMap::with_capacity(items.len());
346    let mut targets = HashSet::with_capacity(items.len());
347    for (index, item) in items.iter().enumerate() {
348        if is_star_item(item) {
349            star = true;
350            continue;
351        }
352        let Expr::Variable(name) = &item.expr else {
353            return None;
354        };
355        // Text render: the rename map is the projection's String column
356        // domain. A source named twice, or a target two sources share, is
357        // declined: the first binds two names to one entity, the second
358        // shadows one of them.
359        let old = name.to_string();
360        let new = item.output_name(index);
361        if renames.insert(old, new.clone()).is_some() || !targets.insert(new) {
362            return None;
363        }
364    }
365    // Under `*` every factor survives, so only identity aliases are a pure
366    // rename — a real one would bind two names to one entity.
367    if star && renames.iter().any(|(old, new)| old != new) {
368        return None;
369    }
370    Some(if star {
371        RenameProjection::Star
372    } else {
373        RenameProjection::Renamed(renames)
374    })
375}
376
377/// Rewrite the factors through one pure-rename `WITH`. The projection
378/// must cover the factors exactly: under `*` every factor survives
379/// unchanged, and without `*` every factor must be renamed — a factor no
380/// item mentions is dropped, and a dropped factor still multiplies the row
381/// space (its emptiness empties the write, its multiplicity scales it —
382/// REL8-2023 issues 72 and 77's WITH shape), which the batched path,
383/// targeting the surviving factors' entities once each, can see neither.
384/// The input is consumed whole, so a decline never leaves a half-rewritten
385/// scope behind.
386fn apply_rename_projection(
387    factors: Vec<Factor>,
388    projection: &RenameProjection,
389) -> Option<Vec<Factor>> {
390    let renames = match projection {
391        RenameProjection::Star => return Some(factors),
392        RenameProjection::Renamed(renames) => renames,
393    };
394    let mut kept = Vec::with_capacity(factors.len());
395    for mut factor in factors {
396        factor.var = renames.get(factor.var.as_str())?.clone();
397        kept.push(factor);
398    }
399    Some(kept)
400}
401
402/// Plan-time detection of a batchable global bulk write (ADR-0209 §1).
403///
404/// Conservative by construction: any deviation from the recognized
405/// shapes — a `WHERE`, an aggregating `WITH`, a graph-sensitive `CREATE`
406/// expression, a `RETURN` after the write, multiple parts, `UNION`,
407/// `NEXT` — yields `None` and the statement runs unbatched.
408impl BulkWrite {
409    /// An O(1) upper bound on the touched-entity count, from the label
410    /// index (plan-time counts, ADR-0218): product of per-factor upper
411    /// bounds for row writes, sum over the named factors for a delete.
412    /// `None` when a factor has no cheap bound (unlabeled rels) — the
413    /// caller then pays the real collection. Overestimates are safe
414    /// (the cost is collecting anyway); underestimates would wrongly
415    /// skip batching, so every arm errs upward.
416    pub fn estimate_upper_bound(&self, graph: &Graph) -> Option<u64> {
417        let factor_bound = |f: &Factor| -> Option<u64> {
418            match &f.source {
419                FactorSource::Nodes { labels } if !labels.is_empty() => {
420                    // intersection ≤ smallest label count
421                    labels.iter().map(|l| graph.label_count(l)).min()
422                }
423                FactorSource::Nodes { .. } => Some(graph.live_node_count() as u64),
424                // no cheap rel-type count index: decline to estimate
425                FactorSource::Rels { .. } => None,
426            }
427        };
428        match &self.kind {
429            // detach work is entities + their incident rels (1 + degree per
430            // node) — label counts give no cheap bound, so decline and let
431            // phase 1's exact total_work() decide.
432            BulkKind::Delete { detach: true, .. } => None,
433            BulkKind::Delete { targets, .. } => self
434                .factors
435                .iter()
436                .filter(|f| targets.contains(&f.var))
437                .try_fold(0u64, |acc, f| {
438                    factor_bound(f).map(|b| acc.saturating_add(b))
439                }),
440            BulkKind::Set { .. } | BulkKind::Remove { .. } | BulkKind::Create { .. } => {
441                self.factors.iter().try_fold(1u64, |acc, f| {
442                    factor_bound(f).map(|b| acc.saturating_mul(b))
443                })
444            }
445        }
446    }
447}
448
449/// Whether two relationship factors of one `MATCH` clause can bind the
450/// same relationship: an empty type list means "any type", and two
451/// non-empty disjoint lists never collide (a relationship carries one
452/// type).
453fn rel_types_overlap(a: &[String], b: &[String]) -> bool {
454    a.is_empty() || b.is_empty() || a.iter().any(|ty| b.contains(ty))
455}
456
457/// Whether any two relationship factors of one `MATCH` clause can bind the
458/// same relationship. Cypher relationship uniqueness forbids it, and the
459/// batched cross product has no such filter (issue 71), so any overlapping
460/// pair declines batching.
461fn breaks_relationship_uniqueness(factors: &[Factor]) -> bool {
462    let mut seen: Vec<&[String]> = Vec::new();
463    for types in factors.iter().filter_map(|factor| match &factor.source {
464        FactorSource::Rels { types } => Some(types.as_slice()),
465        FactorSource::Nodes { .. } => None,
466    }) {
467        if seen.iter().any(|other| rel_types_overlap(other, types)) {
468            return true;
469        }
470        seen.push(types);
471    }
472    false
473}
474
475/// Whether every factor's variable is distinct — a repeated variable is a
476/// self-join, not a cross product of independent factors.
477fn factor_vars_are_distinct(factors: &[Factor]) -> bool {
478    factors
479        .iter()
480        .map(|factor| factor.var.as_str())
481        .collect::<HashSet<_>>()
482        .len()
483        == factors.len()
484}
485
486pub fn analyze_bulk_write(plan: &LogicalPlan) -> Option<BulkWrite> {
487    let clauses = plan.single_part()?;
488    let mut factors: Vec<Factor> = Vec::new();
489    let mut i = 0;
490    while let Some(Clause::Match {
491        optional,
492        patterns,
493        where_clause,
494        search,
495        ..
496    }) = clauses.get(i)
497    {
498        if *optional || where_clause.is_some() || search.is_some() || patterns.is_empty() {
499            return None;
500        }
501        let mut clause_factors: Vec<Factor> = Vec::with_capacity(patterns.len());
502        for pattern in patterns {
503            clause_factors.push(bare_node_factor(pattern).or_else(|| bare_rel_factor(pattern))?);
504        }
505        if breaks_relationship_uniqueness(&clause_factors) {
506            return None;
507        }
508        factors.extend(clause_factors);
509        i += 1;
510    }
511    if factors.is_empty() {
512        return None;
513    }
514    // A repeated variable across patterns is a self-join in the
515    // unbatched engine, not a cross product of independent factors.
516    if !factor_vars_are_distinct(&factors) {
517        return None;
518    }
519    // Pure-rename WITHs only; the write clause references the final
520    // names. The decoder owns the `With` variant test — this loop owns
521    // only the phase boundary: any clause the pure-rename decoder
522    // declines, `With` or not, ends the phase here, and the terminal
523    // checks below decline the leftover shape either way.
524    while let Some(clause) = clauses.get(i) {
525        let Some(projection) = with_rename_projection(clause) else {
526            break;
527        };
528        factors = apply_rename_projection(factors, &projection)?;
529        i += 1;
530    }
531    // Exactly one terminal write clause; nothing may follow it — the
532    // one binding that carries both the arity and the scrutinee.
533    let [write] = &clauses[i..] else {
534        return None;
535    };
536    let scope: HashSet<String> = factors.iter().map(|f| f.var.clone()).collect();
537    // One constructor shape per write kind — eligibility is each
538    // constructor's own `Option`; anything else is not a terminal
539    // write clause, and the recognizer declines.
540    let kind = match write {
541        Clause::Delete {
542            detach,
543            expressions,
544        } => delete_kind(*detach, expressions, &factors),
545        Clause::Set { items } => set_kind(items, &scope),
546        Clause::Remove { items } => remove_kind(items, &scope),
547        Clause::Create { patterns } => create_kind(patterns, &scope),
548        _ => return None,
549    }?;
550    Some(BulkWrite { kind, factors })
551}