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. `None` when the
317/// clause is any of: not a `WITH`; carrying `DISTINCT`, a grouping,
318/// ordering, `SKIP`, `LIMIT`, or `WHERE`; holding an item that is neither
319/// a variable nor `*`; renaming one source twice (two names for one
320/// entity, which the one-entry-per-variable factor list cannot carry);
321/// giving two sources one target (the second would shadow the first); or
322/// pairing `*` with a real (non-identity) alias. The inline comments in the
323/// body own the per-shape reasons.
324fn with_rename_projection(clause: &Clause) -> Option<RenameProjection> {
325 let Clause::With {
326 distinct,
327 group_by,
328 items,
329 order,
330 skip,
331 limit,
332 where_clause,
333 ..
334 } = clause
335 else {
336 return None;
337 };
338 if *distinct
339 || group_by.is_some()
340 || !order.is_empty()
341 || skip.is_some()
342 || limit.is_some()
343 || where_clause.is_some()
344 {
345 return None;
346 }
347 let mut star = false;
348 let mut renames = HashMap::with_capacity(items.len());
349 let mut targets = HashSet::with_capacity(items.len());
350 for (index, item) in items.iter().enumerate() {
351 if is_star_item(item) {
352 star = true;
353 continue;
354 }
355 let Expr::Variable(name) = &item.expr else {
356 return None;
357 };
358 // Text render: the rename map is the projection's String column
359 // domain. A source named twice, or a target two sources share, is
360 // declined: the first binds two names to one entity, the second
361 // shadows one of them.
362 let old = name.to_string();
363 let new = item.output_name(index);
364 if renames.insert(old, new.clone()).is_some() || !targets.insert(new) {
365 return None;
366 }
367 }
368 // Under `*` every factor survives, so only identity aliases are a pure
369 // rename — a real one would bind two names to one entity.
370 if star && renames.iter().any(|(old, new)| old != new) {
371 return None;
372 }
373 Some(if star {
374 RenameProjection::Star
375 } else {
376 RenameProjection::Renamed(renames)
377 })
378}
379
380/// Rewrite the factors through one pure-rename `WITH`. The projection
381/// must cover the factors exactly: under `*` every factor survives
382/// unchanged, and without `*` every factor must be renamed — a factor no
383/// item mentions is dropped, and a dropped factor still multiplies the row
384/// space (its emptiness empties the write, its multiplicity scales it —
385/// REL8-2023 issues 72 and 77's WITH shape), which the batched path,
386/// targeting the surviving factors' entities once each, can see neither.
387/// The input is consumed whole, so a decline never leaves a half-rewritten
388/// scope behind.
389fn apply_rename_projection(
390 factors: Vec<Factor>,
391 projection: &RenameProjection,
392) -> Option<Vec<Factor>> {
393 let renames = match projection {
394 RenameProjection::Star => return Some(factors),
395 RenameProjection::Renamed(renames) => renames,
396 };
397 let mut kept = Vec::with_capacity(factors.len());
398 for mut factor in factors {
399 factor.var = renames.get(factor.var.as_str())?.clone();
400 kept.push(factor);
401 }
402 Some(kept)
403}
404
405/// Plan-time detection of a batchable global bulk write (ADR-0209 §1).
406///
407/// Conservative by construction: any deviation from the recognized
408/// shapes — a `WHERE`, an aggregating `WITH`, a graph-sensitive `CREATE`
409/// expression, a `RETURN` after the write, multiple parts, `UNION`,
410/// `NEXT` — yields `None` and the statement runs unbatched.
411impl BulkWrite {
412 /// An O(1) upper bound on the touched-entity count, from the label
413 /// index (plan-time counts, ADR-0218): product of per-factor upper
414 /// bounds for row writes, sum over the named factors for a delete.
415 /// `None` when a factor has no cheap bound (unlabeled rels) — the
416 /// caller then pays the real collection. Overestimates are safe
417 /// (the cost is collecting anyway); underestimates would wrongly
418 /// skip batching, so every arm errs upward.
419 pub fn estimate_upper_bound(&self, graph: &Graph) -> Option<u64> {
420 let factor_bound = |f: &Factor| -> Option<u64> {
421 match &f.source {
422 FactorSource::Nodes { labels } if !labels.is_empty() => {
423 // intersection ≤ smallest label count
424 labels.iter().map(|l| graph.label_count(l)).min()
425 }
426 FactorSource::Nodes { .. } => Some(graph.live_node_count() as u64),
427 // no cheap rel-type count index: decline to estimate
428 FactorSource::Rels { .. } => None,
429 }
430 };
431 match &self.kind {
432 // detach work is entities + their incident rels (1 + degree per
433 // node) — label counts give no cheap bound, so decline and let
434 // phase 1's exact total_work() decide.
435 BulkKind::Delete { detach: true, .. } => None,
436 BulkKind::Delete { targets, .. } => self
437 .factors
438 .iter()
439 .filter(|f| targets.contains(&f.var))
440 .try_fold(0u64, |acc, f| {
441 factor_bound(f).map(|b| acc.saturating_add(b))
442 }),
443 BulkKind::Set { .. } | BulkKind::Remove { .. } | BulkKind::Create { .. } => {
444 self.factors.iter().try_fold(1u64, |acc, f| {
445 factor_bound(f).map(|b| acc.saturating_mul(b))
446 })
447 }
448 }
449 }
450}
451
452/// Whether two relationship factors of one `MATCH` clause can bind the
453/// same relationship: an empty type list means "any type", and two
454/// non-empty disjoint lists never collide (a relationship carries one
455/// type).
456fn rel_types_overlap(a: &[String], b: &[String]) -> bool {
457 a.is_empty() || b.is_empty() || a.iter().any(|ty| b.contains(ty))
458}
459
460/// Whether any two relationship factors of one `MATCH` clause can bind the
461/// same relationship. Cypher relationship uniqueness forbids it, and the
462/// batched cross product has no such filter (issue 71), so any overlapping
463/// pair declines batching.
464fn breaks_relationship_uniqueness(factors: &[Factor]) -> bool {
465 let mut seen: Vec<&[String]> = Vec::new();
466 for types in factors.iter().filter_map(|factor| match &factor.source {
467 FactorSource::Rels { types } => Some(types.as_slice()),
468 FactorSource::Nodes { .. } => None,
469 }) {
470 if seen.iter().any(|other| rel_types_overlap(other, types)) {
471 return true;
472 }
473 seen.push(types);
474 }
475 false
476}
477
478/// Whether every factor's variable is distinct — a repeated variable is a
479/// self-join, not a cross product of independent factors.
480fn factor_vars_are_distinct(factors: &[Factor]) -> bool {
481 factors
482 .iter()
483 .map(|factor| factor.var.as_str())
484 .collect::<HashSet<_>>()
485 .len()
486 == factors.len()
487}
488
489pub fn analyze_bulk_write(plan: &LogicalPlan) -> Option<BulkWrite> {
490 let clauses = plan.single_part()?;
491 let mut factors: Vec<Factor> = Vec::new();
492 let mut i = 0;
493 while let Some(Clause::Match {
494 optional,
495 patterns,
496 where_clause,
497 search,
498 ..
499 }) = clauses.get(i)
500 {
501 if *optional || where_clause.is_some() || search.is_some() || patterns.is_empty() {
502 return None;
503 }
504 let mut clause_factors: Vec<Factor> = Vec::with_capacity(patterns.len());
505 for pattern in patterns {
506 clause_factors.push(bare_node_factor(pattern).or_else(|| bare_rel_factor(pattern))?);
507 }
508 if breaks_relationship_uniqueness(&clause_factors) {
509 return None;
510 }
511 factors.extend(clause_factors);
512 i += 1;
513 }
514 if factors.is_empty() {
515 return None;
516 }
517 // A repeated variable across patterns is a self-join in the
518 // unbatched engine, not a cross product of independent factors.
519 if !factor_vars_are_distinct(&factors) {
520 return None;
521 }
522 // Pure-rename WITHs only; the write clause references the final
523 // names. The decoder owns the `With` variant test — this loop owns
524 // only the phase boundary: any clause the pure-rename decoder
525 // declines, `With` or not, ends the phase here, and the terminal
526 // checks below decline the leftover shape either way.
527 while let Some(clause) = clauses.get(i) {
528 let Some(projection) = with_rename_projection(clause) else {
529 break;
530 };
531 factors = apply_rename_projection(factors, &projection)?;
532 i += 1;
533 }
534 // Exactly one terminal write clause; nothing may follow it — the
535 // one binding that carries both the arity and the scrutinee.
536 let [write] = &clauses[i..] else {
537 return None;
538 };
539 let scope: HashSet<String> = factors.iter().map(|f| f.var.clone()).collect();
540 // One constructor shape per write kind — eligibility is each
541 // constructor's own `Option`; anything else is not a terminal
542 // write clause, and the recognizer declines.
543 let kind = match write {
544 Clause::Delete {
545 detach,
546 expressions,
547 } => delete_kind(*detach, expressions, &factors),
548 Clause::Set { items } => set_kind(items, &scope),
549 Clause::Remove { items } => remove_kind(items, &scope),
550 Clause::Create { patterns } => create_kind(patterns, &scope),
551 _ => return None,
552 }?;
553 Some(BulkWrite { kind, factors })
554}