relate-executor 1.5.0

In-memory graph and Cypher physical executor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! Batched execution of global bulk writes (ADR-0209, LABS-263).
//!
//! A statement like `MATCH (n) DETACH DELETE n` or
//! `MATCH (n) MATCH (m) WITH n AS a, m AS b CREATE (a)-[:TAGGED]->(b)`
//! has no selective anchor: it touches every matched entity, and running
//! it as one giant transaction materializes the whole redo in a single
//! scratch and lands it as a single WAL record (which can cross the
//! 64 MiB payload limit or exhaust memory). This module detects those
//! shapes at plan time — conservatively, only when per-row effects are
//! independent of batch boundaries — and provides the pieces the
//! auto-commit path (`relate::commit`) needs to run them in bounded
//! batches, one WAL commit per batch:
//!
//! - [`analyze_bulk_write`] — plan-shape detection (this file);
//! - [`BulkWrite::collect_targets`] — phase 1: snapshot the matched
//!   entity id space (memory O(entities), never O(cross product));
//! - [`BulkWrite::execute_chunk`] — phase 2: apply up to `budget` work
//!   units starting at `cursor`, on the caller's scratch.
//!
//! The two phases live in [`run`]; this file holds the plan analysis.
//!
//! Semantics: the matched set is fixed before the first batch writes,
//! and every eligible write's per-row effect is independent of when
//! sibling rows ran, so the final state and the summed write statistics
//! equal the unbatched run. On the error path earlier batches stay
//! committed — the documented `CALL { } IN TRANSACTIONS` trade-off. One
//! error is preflighted before the first commit: a non-`DETACH` node
//! `DELETE`'s `DeleteConnectedNode` check. That keeps the statement
//! atomic for this error only as long as no concurrent writer adds a
//! relationship after the preflight snapshot; such a race surfaces as a
//! mid-run error with earlier batches committed, like any other
//! mid-statement failure.

use std::collections::{HashMap, HashSet};

use relate_ir::{Clause, Direction, Expr, PathPattern, RemoveItem, SetItem};
use relate_names::SmallName;

use crate::graph::Graph;
use relate_planner::LogicalPlan;

use super::create_admission::{
    compact_pattern, create_patterns_eligible, node_is_bare_endpoint, refs_within,
    rel_has_static_edge_shape,
};
use super::label_expr_ok;
use super::scope::is_star_item;

mod run;

pub use run::{BulkCursor, BulkTargets};

#[cfg(test)]
mod tests;

/// Default work estimate at or above which an eligible statement is
/// batched instead of running as one transaction.
pub const DEFAULT_BATCH_THRESHOLD: u64 = 10_000;
/// Default per-batch work budget (estimated touched entities).
pub const DEFAULT_BATCH_BUDGET: u64 = 25_000;

/// One matched variable's identity source: a bare node pattern
/// `(<var> [:labels…])` or a bare relationship pattern
/// `()-[<var> [:types…]]->()`.
#[derive(Debug, Clone)]
pub(super) enum FactorSource {
    Nodes { labels: Vec<String> },
    Rels { types: Vec<String> },
}

/// A matched variable and where its entities come from.
#[derive(Debug, Clone)]
pub(super) struct Factor {
    var: String,
    source: FactorSource,
}

/// The write clause of an eligible statement, plus what it may
/// reference: one variant per write flavor, carrying the payload the
/// execution arm needs so execution matches one enum exactly once.
#[derive(Debug, Clone)]
pub(super) enum BulkKind {
    Delete {
        detach: bool,
        /// The variables the `DELETE` names; factors not named keep
        /// their entities.
        targets: HashSet<String>,
    },
    Set {
        items: Vec<SetItem>,
    },
    Remove {
        items: Vec<RemoveItem>,
    },
    Create {
        patterns: Vec<PathPattern>,
    },
}

/// A plan-time eligible global bulk write (ADR-0209 §1).
#[derive(Debug, Clone)]
pub struct BulkWrite {
    pub(super) kind: BulkKind,
    pub(super) factors: Vec<Factor>,
}

/// Whether `pattern` is a bare node pattern `(<var> [:labels…])`: named,
/// no relationship, no properties, no predicates anywhere, no label
/// expression, no path variable, no GPM-only features.
fn bare_node_factor(pattern: &PathPattern) -> Option<Factor> {
    if !compact_pattern(pattern) || !pattern.rels.is_empty() || pattern.nodes.len() != 1 {
        return None;
    }
    let node = &pattern.nodes[0];
    if !label_expr_ok(&node.label_expr, &node.labels)
        || node.properties.is_some()
        || node.where_clause.is_some()
    {
        return None;
    }
    Some(Factor {
        // Text render: the bulk factor's label/type lists feed the
        // store's count APIs (String domain).
        var: node.variable.as_ref()?.to_string(),
        source: FactorSource::Nodes {
            labels: node.label_names().map(|label| label.to_string()).collect(),
        },
    })
}

/// Whether `pattern` is a bare directed relationship pattern
/// `()-[<var> [:types…]]->()`: both endpoints anonymous and bare, the
/// relationship named, fixed length, no properties or predicates.
fn bare_rel_factor(pattern: &PathPattern) -> Option<Factor> {
    if !compact_pattern(pattern) || pattern.nodes.len() != 2 || pattern.rels.len() != 1 {
        return None;
    }
    for node in &pattern.nodes {
        // Anonymous endpoints only, each bare (no labels, properties or
        // predicate of its own).
        if node.variable.is_some() || !node_is_bare_endpoint(node) {
            return None;
        }
    }
    let rel = &pattern.rels[0];
    // An undirected pattern matches every non-loop relationship once per
    // orientation; the factor's target set holds each id once (issue 70),
    // so the shape stays on the unbatched path. A property map would make
    // the row's effect depend on a per-element value the factor target
    // space does not carry.
    if rel.direction == Direction::Both
        || !rel_has_static_edge_shape(rel)
        || rel.properties.is_some()
    {
        return None;
    }
    Some(Factor {
        var: rel.variable.as_ref()?.to_string(),
        source: FactorSource::Rels {
            types: rel.type_names().map(|ty| ty.to_string()).collect(),
        },
    })
}

/// The variable a `SET`/`REMOVE` target expression roots at, for the bulk
/// eligibility rule below: `n`, `n.k`, or `n[k]` with `n` a plain
/// variable. Deliberately one level deep — a deeper access chain
/// (`n[x][y]`) is not eligible here, because the bulk path's per-row
/// effect must depend on a single matched variable. The recursive twin
/// ([`relate_ir::root_variable`], REL8-1813) answers the different
/// question the write-target class decision asks — "is this target
/// variable-rooted at all" — and must not replace this test.
fn target_root_var(expr: &Expr) -> Option<&SmallName> {
    match expr {
        Expr::Variable(name) => Some(name),
        Expr::Property { expr, .. } | Expr::DynamicProperty { expr, .. } => match expr.as_ref() {
            Expr::Variable(name) => Some(name),
            _ => None,
        },
        _ => None,
    }
}

/// Shared per-item eligibility rule for `SET`/`REMOVE`: every target
/// roots at a matched variable, and every value/dynamic-key expression
/// references at most that same variable (per-row effects then cannot
/// depend on when sibling rows ran — ADR-0209 §1). Each item arrives as
/// its target expression plus the value/dynamic-key expressions to
/// scope-check.
fn per_item_eligible<'a>(
    items: impl IntoIterator<Item = (&'a Expr, Vec<&'a Expr>)>,
    scope: &HashSet<String>,
) -> bool {
    items.into_iter().all(|(target, value_exprs)| {
        let Some(root) = target_root_var(target) else {
            return false;
        };
        if !root.with_str(|text| scope.contains(text)) {
            return false;
        }
        // Text render: the allowed-set is the refs_within String domain.
        let allowed = HashSet::from([root.to_string()]);
        value_exprs.iter().all(|expr| refs_within(expr, &allowed))
    })
}

/// Whether the `SET` items are batch-safe (see [`per_item_eligible`]).
fn set_items_eligible(items: &[SetItem], scope: &HashSet<String>) -> bool {
    !items.is_empty()
        && per_item_eligible(
            items.iter().map(|item| match item {
                SetItem::Property { target, value } => {
                    let mut exprs = vec![value];
                    if let Expr::DynamicProperty { key, .. } = target {
                        exprs.push(key);
                    }
                    (target, exprs)
                }
                SetItem::ReplaceAll { target, value } => (target, vec![value]),
                SetItem::MergeMap { target, value } => (target, vec![value]),
                SetItem::Labels { target, .. } => (target, Vec::new()),
                SetItem::LabelsFunction { target, value, .. } => (target, vec![value]),
            }),
            scope,
        )
}

/// Whether the `REMOVE` items are batch-safe (same target rule; the only
/// expressions are dynamic property keys).
fn remove_items_eligible(items: &[RemoveItem], scope: &HashSet<String>) -> bool {
    !items.is_empty()
        && per_item_eligible(
            items.iter().map(|item| match item {
                RemoveItem::Property { target } => {
                    let exprs = match target {
                        Expr::DynamicProperty { key, .. } => vec![key.as_ref()],
                        _ => Vec::new(),
                    };
                    (target, exprs)
                }
                RemoveItem::Labels { target, .. } => (target, Vec::new()),
            }),
            scope,
        )
}

/// The `SET` target kind — eligible when every item reads only the
/// final scope's variables ([`set_items_eligible`]'s own contract).
fn set_kind(items: &[SetItem], scope: &HashSet<String>) -> Option<BulkKind> {
    set_items_eligible(items, scope).then(|| BulkKind::Set {
        items: items.to_vec(),
    })
}

/// The `REMOVE` target kind — eligible when every item reads only the
/// final scope's variables ([`remove_items_eligible`]'s own contract).
fn remove_kind(items: &[RemoveItem], scope: &HashSet<String>) -> Option<BulkKind> {
    remove_items_eligible(items, scope).then(|| BulkKind::Remove {
        items: items.to_vec(),
    })
}

/// The `CREATE` target kind — eligible when every pattern's refs stay
/// within the final scope ([`create_patterns_eligible`]'s own
/// contract).
fn create_kind(patterns: &[PathPattern], scope: &HashSet<String>) -> Option<BulkKind> {
    create_patterns_eligible(patterns, scope).then(|| BulkKind::Create {
        patterns: patterns.to_vec(),
    })
}

/// Whether the `DELETE` clause is batch-safe, and its kind when it is:
/// every expression must be a plain variable naming a matched factor
/// (one walk collects the named factors and classifies their sources),
/// and — unless `DETACH` — the targets may not mix nodes and
/// relationships: the connectedness preflight would have to ignore the
/// statement's own relationship targets, so that shape stays on the
/// unbatched path.
fn delete_kind(detach: bool, expressions: &[Expr], factors: &[Factor]) -> Option<BulkKind> {
    if expressions.is_empty() {
        return None;
    }
    let mut named = HashSet::with_capacity(expressions.len());
    let mut touches_nodes = false;
    let mut touches_rels = false;
    for expr in expressions {
        let Expr::Variable(name) = expr else {
            return None;
        };
        let factor = factors.iter().find(|f| name == f.var.as_str())?;
        match factor.source {
            FactorSource::Nodes { .. } => touches_nodes = true,
            FactorSource::Rels { .. } => touches_rels = true,
        }
        named.insert(name.to_string());
    }
    if !detach && touches_nodes && touches_rels {
        return None;
    }
    Some(BulkKind::Delete {
        detach,
        targets: named,
    })
}

/// A pure-rename `WITH` clause's shape: `*` (every factor survives, its
/// aliases identity only — a real rename would bind two names to one
/// entity) or the old → new map of its explicit variable items (the
/// decoder declines a second target for one source, and two sources
/// sharing a target — either would shadow a surviving factor).
enum RenameProjection {
    Star,
    Renamed(HashMap<String, String>),
}

/// Whether a `WITH` clause is a pure rename projection. `None` when the
/// clause is any of: not a `WITH`; carrying `DISTINCT`, a grouping,
/// ordering, `SKIP`, `LIMIT`, or `WHERE`; holding an item that is neither
/// a variable nor `*`; renaming one source twice (two names for one
/// entity, which the one-entry-per-variable factor list cannot carry);
/// giving two sources one target (the second would shadow the first); or
/// pairing `*` with a real (non-identity) alias. The inline comments in the
/// body own the per-shape reasons.
fn with_rename_projection(clause: &Clause) -> Option<RenameProjection> {
    let Clause::With {
        distinct,
        group_by,
        items,
        order,
        skip,
        limit,
        where_clause,
        ..
    } = clause
    else {
        return None;
    };
    if *distinct
        || group_by.is_some()
        || !order.is_empty()
        || skip.is_some()
        || limit.is_some()
        || where_clause.is_some()
    {
        return None;
    }
    let mut star = false;
    let mut renames = HashMap::with_capacity(items.len());
    let mut targets = HashSet::with_capacity(items.len());
    for (index, item) in items.iter().enumerate() {
        if is_star_item(item) {
            star = true;
            continue;
        }
        let Expr::Variable(name) = &item.expr else {
            return None;
        };
        // Text render: the rename map is the projection's String column
        // domain. A source named twice, or a target two sources share, is
        // declined: the first binds two names to one entity, the second
        // shadows one of them.
        let old = name.to_string();
        let new = item.output_name(index);
        if renames.insert(old, new.clone()).is_some() || !targets.insert(new) {
            return None;
        }
    }
    // Under `*` every factor survives, so only identity aliases are a pure
    // rename — a real one would bind two names to one entity.
    if star && renames.iter().any(|(old, new)| old != new) {
        return None;
    }
    Some(if star {
        RenameProjection::Star
    } else {
        RenameProjection::Renamed(renames)
    })
}

/// Rewrite the factors through one pure-rename `WITH`. The projection
/// must cover the factors exactly: under `*` every factor survives
/// unchanged, and without `*` every factor must be renamed — a factor no
/// item mentions is dropped, and a dropped factor still multiplies the row
/// space (its emptiness empties the write, its multiplicity scales it —
/// REL8-2023 issues 72 and 77's WITH shape), which the batched path,
/// targeting the surviving factors' entities once each, can see neither.
/// The input is consumed whole, so a decline never leaves a half-rewritten
/// scope behind.
fn apply_rename_projection(
    factors: Vec<Factor>,
    projection: &RenameProjection,
) -> Option<Vec<Factor>> {
    let renames = match projection {
        RenameProjection::Star => return Some(factors),
        RenameProjection::Renamed(renames) => renames,
    };
    let mut kept = Vec::with_capacity(factors.len());
    for mut factor in factors {
        factor.var = renames.get(factor.var.as_str())?.clone();
        kept.push(factor);
    }
    Some(kept)
}

/// Plan-time detection of a batchable global bulk write (ADR-0209 §1).
///
/// Conservative by construction: any deviation from the recognized
/// shapes — a `WHERE`, an aggregating `WITH`, a graph-sensitive `CREATE`
/// expression, a `RETURN` after the write, multiple parts, `UNION`,
/// `NEXT` — yields `None` and the statement runs unbatched.
impl BulkWrite {
    /// An O(1) upper bound on the touched-entity count, from the label
    /// index (plan-time counts, ADR-0218): product of per-factor upper
    /// bounds for row writes, sum over the named factors for a delete.
    /// `None` when a factor has no cheap bound (unlabeled rels) — the
    /// caller then pays the real collection. Overestimates are safe
    /// (the cost is collecting anyway); underestimates would wrongly
    /// skip batching, so every arm errs upward.
    pub fn estimate_upper_bound(&self, graph: &Graph) -> Option<u64> {
        let factor_bound = |f: &Factor| -> Option<u64> {
            match &f.source {
                FactorSource::Nodes { labels } if !labels.is_empty() => {
                    // intersection ≤ smallest label count
                    labels.iter().map(|l| graph.label_count(l)).min()
                }
                FactorSource::Nodes { .. } => Some(graph.live_node_count() as u64),
                // no cheap rel-type count index: decline to estimate
                FactorSource::Rels { .. } => None,
            }
        };
        match &self.kind {
            // detach work is entities + their incident rels (1 + degree per
            // node) — label counts give no cheap bound, so decline and let
            // phase 1's exact total_work() decide.
            BulkKind::Delete { detach: true, .. } => None,
            BulkKind::Delete { targets, .. } => self
                .factors
                .iter()
                .filter(|f| targets.contains(&f.var))
                .try_fold(0u64, |acc, f| {
                    factor_bound(f).map(|b| acc.saturating_add(b))
                }),
            BulkKind::Set { .. } | BulkKind::Remove { .. } | BulkKind::Create { .. } => {
                self.factors.iter().try_fold(1u64, |acc, f| {
                    factor_bound(f).map(|b| acc.saturating_mul(b))
                })
            }
        }
    }
}

/// Whether two relationship factors of one `MATCH` clause can bind the
/// same relationship: an empty type list means "any type", and two
/// non-empty disjoint lists never collide (a relationship carries one
/// type).
fn rel_types_overlap(a: &[String], b: &[String]) -> bool {
    a.is_empty() || b.is_empty() || a.iter().any(|ty| b.contains(ty))
}

/// Whether any two relationship factors of one `MATCH` clause can bind the
/// same relationship. Cypher relationship uniqueness forbids it, and the
/// batched cross product has no such filter (issue 71), so any overlapping
/// pair declines batching.
fn breaks_relationship_uniqueness(factors: &[Factor]) -> bool {
    let mut seen: Vec<&[String]> = Vec::new();
    for types in factors.iter().filter_map(|factor| match &factor.source {
        FactorSource::Rels { types } => Some(types.as_slice()),
        FactorSource::Nodes { .. } => None,
    }) {
        if seen.iter().any(|other| rel_types_overlap(other, types)) {
            return true;
        }
        seen.push(types);
    }
    false
}

/// Whether every factor's variable is distinct — a repeated variable is a
/// self-join, not a cross product of independent factors.
fn factor_vars_are_distinct(factors: &[Factor]) -> bool {
    factors
        .iter()
        .map(|factor| factor.var.as_str())
        .collect::<HashSet<_>>()
        .len()
        == factors.len()
}

pub fn analyze_bulk_write(plan: &LogicalPlan) -> Option<BulkWrite> {
    let clauses = plan.single_part()?;
    let mut factors: Vec<Factor> = Vec::new();
    let mut i = 0;
    while let Some(Clause::Match {
        optional,
        patterns,
        where_clause,
        search,
        ..
    }) = clauses.get(i)
    {
        if *optional || where_clause.is_some() || search.is_some() || patterns.is_empty() {
            return None;
        }
        let mut clause_factors: Vec<Factor> = Vec::with_capacity(patterns.len());
        for pattern in patterns {
            clause_factors.push(bare_node_factor(pattern).or_else(|| bare_rel_factor(pattern))?);
        }
        if breaks_relationship_uniqueness(&clause_factors) {
            return None;
        }
        factors.extend(clause_factors);
        i += 1;
    }
    if factors.is_empty() {
        return None;
    }
    // A repeated variable across patterns is a self-join in the
    // unbatched engine, not a cross product of independent factors.
    if !factor_vars_are_distinct(&factors) {
        return None;
    }
    // Pure-rename WITHs only; the write clause references the final
    // names. The decoder owns the `With` variant test — this loop owns
    // only the phase boundary: any clause the pure-rename decoder
    // declines, `With` or not, ends the phase here, and the terminal
    // checks below decline the leftover shape either way.
    while let Some(clause) = clauses.get(i) {
        let Some(projection) = with_rename_projection(clause) else {
            break;
        };
        factors = apply_rename_projection(factors, &projection)?;
        i += 1;
    }
    // Exactly one terminal write clause; nothing may follow it — the
    // one binding that carries both the arity and the scrutinee.
    let [write] = &clauses[i..] else {
        return None;
    };
    let scope: HashSet<String> = factors.iter().map(|f| f.var.clone()).collect();
    // One constructor shape per write kind — eligibility is each
    // constructor's own `Option`; anything else is not a terminal
    // write clause, and the recognizer declines.
    let kind = match write {
        Clause::Delete {
            detach,
            expressions,
        } => delete_kind(*detach, expressions, &factors),
        Clause::Set { items } => set_kind(items, &scope),
        Clause::Remove { items } => remove_kind(items, &scope),
        Clause::Create { patterns } => create_kind(patterns, &scope),
        _ => return None,
    }?;
    Some(BulkWrite { kind, factors })
}