Skip to main content

relate_executor/exec/bulk/
run.rs

1//! The runtime half of batched bulk writes (ADR-0209): the snapshotted
2//! target space, the cursor, the budgeted loop, and [`BulkWrite`]'s
3//! phase-1/phase-2 methods. Plan analysis lives in [`super`].
4
5use std::collections::{BTreeMap, HashSet};
6
7use relate_core::{NodeId, RelId, Result, Value};
8use relate_ir::Direction;
9
10use crate::graph::Graph;
11use crate::overlay::ExecGraph;
12use crate::row::Row;
13
14use super::super::create::create_patterns;
15use super::super::write::{apply_resolved_removes, apply_sets, resolve_removes};
16use super::{BulkKind, BulkWrite, FactorSource};
17
18/// Cancellation-check cadence of the budgeted loop: the token is polled
19/// once per this many steps.
20const CANCEL_CHECK_STRIDE: u64 = 1024;
21
22/// One deduplicated `DELETE` target. The node/relationship distinction
23/// is the variant, keeping the two id namespaces apart; a node's `work`
24/// estimate is 1 + incident-degree, a relationship's is uniformly 1.
25#[derive(Debug, Clone, Copy)]
26enum BulkEntity {
27    Node { id: NodeId, work: u64 },
28    Rel { id: RelId },
29}
30
31impl BulkEntity {
32    fn work(&self) -> u64 {
33        match self {
34            Self::Node { work, .. } => *work,
35            Self::Rel { .. } => 1,
36        }
37    }
38}
39
40/// The snapshotted target space plus the write payload it drives. Each
41/// variant carries everything its execution arm needs, so there is no
42/// kind/targets pairing to get wrong.
43#[derive(Debug)]
44enum TargetsInner {
45    /// `DELETE`: deduplicated entities in id order (nodes first).
46    Delete {
47        detach: bool,
48        entities: Vec<BulkEntity>,
49    },
50    /// `SET`: one sorted id vector per factor; the row space is their
51    /// cartesian product (never materialized).
52    Set {
53        items: Vec<relate_ir::SetItem>,
54        factors: Vec<Vec<i64>>,
55    },
56    /// `REMOVE`: same row space as `SET`.
57    Remove {
58        items: Vec<relate_ir::RemoveItem>,
59        factors: Vec<Vec<i64>>,
60    },
61    /// `CREATE`: same row space as `SET`.
62    Create {
63        patterns: Vec<relate_ir::PathPattern>,
64        factors: Vec<Vec<i64>>,
65    },
66}
67
68/// The snapshotted target identity space of a [`BulkWrite`] (phase 1).
69/// Opaque: the only public fact is [`BulkTargets::total_work`].
70#[derive(Debug)]
71pub struct BulkTargets(TargetsInner);
72
73impl BulkTargets {
74    /// The estimated touched-entity count used against the batching
75    /// threshold: entity count plus incident relationships for `DELETE`,
76    /// the factor product for the row-driven writes.
77    pub fn total_work(&self) -> u64 {
78        match &self.0 {
79            TargetsInner::Delete { entities, .. } => entities
80                .iter()
81                .map(BulkEntity::work)
82                .fold(0u64, u64::saturating_add),
83            TargetsInner::Set { factors, .. }
84            | TargetsInner::Remove { factors, .. }
85            | TargetsInner::Create { factors, .. } => factors
86                .iter()
87                .map(|ids| ids.len() as u64)
88                .fold(1u64, u64::saturating_mul),
89        }
90    }
91}
92
93/// Cursor into the target space: the next entity index (`DELETE`) or
94/// combination index (row-driven writes) to process.
95#[derive(Debug, Default)]
96pub struct BulkCursor {
97    next: u64,
98}
99
100/// The budgeted loop both phase-2 arms share: cancel-check every
101/// [`CANCEL_CHECK_STRIDE`] steps, advance the cursor, accumulate the
102/// work `step` reports, and stop once `budget` work units are spent or
103/// the `total`-sized space is exhausted. Returns `true` when the space
104/// is exhausted.
105fn run_budgeted(
106    view: &ExecGraph<'_>,
107    cursor: &mut BulkCursor,
108    total: u64,
109    budget: u64,
110    mut step: impl FnMut(u64) -> Result<u64>,
111) -> Result<bool> {
112    let mut spent = 0u64;
113    while cursor.next < total {
114        if cursor.next % CANCEL_CHECK_STRIDE == 0 {
115            view.check_cancelled()?;
116        }
117        let work = step(cursor.next)?;
118        cursor.next += 1;
119        spent = spent.saturating_add(work);
120        if spent >= budget {
121            break;
122        }
123    }
124    Ok(cursor.next >= total)
125}
126
127impl BulkWrite {
128    /// Phase 1: snapshot the matched entity id space at `snapshot_ts`.
129    /// Returns `Ok(None)` when the catalog holds any constraint: batched
130    /// commits validate per batch, so constrained catalogs keep the
131    /// unbatched atomic path (ADR-0209 §1). A non-`DETACH` node delete
132    /// preflights `DeleteConnectedNode` across every target here, before
133    /// the first batch commits.
134    pub fn collect_targets(&self, graph: &Graph, snapshot_ts: u64) -> Result<Option<BulkTargets>> {
135        if !graph.named_constraints().is_empty() {
136            return Ok(None);
137        }
138        let view = ExecGraph::read_at(graph, snapshot_ts);
139        let mut factors = Vec::with_capacity(self.factors.len());
140        for factor in &self.factors {
141            let ids = match &factor.source {
142                // Labeled/typed factors go through the interned-id
143                // probes; only the untyped/unlabeled factors pay a full
144                // sweep.
145                FactorSource::Nodes { labels } if !labels.is_empty() => {
146                    let mut sets: Vec<Vec<NodeId>> = labels
147                        .iter()
148                        .map(|label| graph.node_ids_with_label_at(label, snapshot_ts))
149                        .collect();
150                    sets.sort_by_key(Vec::len);
151                    let (smallest, rest) = sets.split_first().expect("non-empty labels");
152                    let rest: Vec<HashSet<NodeId>> = rest
153                        .iter()
154                        .map(|ids| ids.iter().copied().collect())
155                        .collect();
156                    smallest
157                        .iter()
158                        .copied()
159                        .filter(|id| rest.iter().all(|set| set.contains(id)))
160                        .collect()
161                }
162                FactorSource::Nodes { .. } => view.all_node_ids(),
163                FactorSource::Rels { types } if !types.is_empty() => {
164                    let mut ids: Vec<RelId> = types
165                        .iter()
166                        .flat_map(|rel_type| graph.rel_ids_of_type_at(rel_type, snapshot_ts))
167                        .collect();
168                    ids.sort_unstable();
169                    ids.dedup();
170                    ids
171                }
172                FactorSource::Rels { .. } => view.all_rel_ids(),
173            };
174            factors.push(ids);
175        }
176        let inner = match &self.kind {
177            BulkKind::Delete { detach, targets } => {
178                self.collect_delete_targets(&view, *detach, targets, &factors)?
179            }
180            BulkKind::Set { items } => TargetsInner::Set {
181                items: items.clone(),
182                factors,
183            },
184            BulkKind::Remove { items } => TargetsInner::Remove {
185                items: items.clone(),
186                factors,
187            },
188            BulkKind::Create { patterns } => TargetsInner::Create {
189                patterns: patterns.clone(),
190                factors,
191            },
192        };
193        Ok(Some(BulkTargets(inner)))
194    }
195
196    /// The `DELETE` target space: gather the ids of the factors the
197    /// `DELETE` names (deduplicated across the possibly cross-product
198    /// row space — deleting an entity is idempotent, so each id is
199    /// processed once), preflight `DeleteConnectedNode` for a
200    /// non-`DETACH` delete, and estimate each entity's work.
201    fn collect_delete_targets(
202        &self,
203        view: &ExecGraph<'_>,
204        detach: bool,
205        targets: &HashSet<String>,
206        factor_ids: &[Vec<i64>],
207    ) -> Result<TargetsInner> {
208        let mut node_ids: Vec<NodeId> = Vec::new();
209        let mut rel_ids: Vec<RelId> = Vec::new();
210        for (factor, ids) in self.factors.iter().zip(factor_ids) {
211            if !targets.contains(&factor.var) {
212                continue;
213            }
214            match factor.source {
215                FactorSource::Nodes { .. } => node_ids.extend_from_slice(ids),
216                FactorSource::Rels { .. } => rel_ids.extend_from_slice(ids),
217            }
218        }
219        node_ids.sort_unstable();
220        node_ids.dedup();
221        rel_ids.sort_unstable();
222        rel_ids.dedup();
223        if !detach {
224            // Preflight the DeleteConnectedNode error before the first
225            // batch commits, keeping the statement atomic for this error
226            // while no concurrent writer adds a relationship after this
227            // snapshot.
228            for &id in &node_ids {
229                let connected = view
230                    .try_find_neighbor(id, Direction::Both, &[], |_| Ok::<bool, ()>(true))
231                    .is_ok_and(|hit| hit.is_some());
232                if connected {
233                    return Err(crate::graph::delete_connected_node_error());
234                }
235            }
236        }
237        let mut entities = Vec::with_capacity(node_ids.len() + rel_ids.len());
238        for id in node_ids {
239            let work = if detach {
240                1u64.saturating_add(view.adj_len(id, Direction::Both) as u64)
241            } else {
242                1
243            };
244            entities.push(BulkEntity::Node { id, work });
245        }
246        entities.extend(rel_ids.into_iter().map(|id| BulkEntity::Rel { id }));
247        Ok(TargetsInner::Delete { detach, entities })
248    }
249
250    /// Phase 2: apply up to `budget` work units starting at `cursor` on
251    /// the caller's write view (which carries the cancellation token).
252    /// Returns `true` when the target space is exhausted. The caller
253    /// commits the view's scratch per chunk.
254    pub fn execute_chunk(
255        &self,
256        view: &ExecGraph<'_>,
257        targets: &BulkTargets,
258        cursor: &mut BulkCursor,
259        budget: u64,
260        params: &BTreeMap<String, Value>,
261    ) -> Result<bool> {
262        match &targets.0 {
263            TargetsInner::Delete { detach, entities } => {
264                let detach = *detach;
265                run_budgeted(view, cursor, entities.len() as u64, budget, |i| {
266                    let entity = entities[i as usize];
267                    match entity {
268                        BulkEntity::Node { id, .. } => view.delete_node(id, detach)?,
269                        BulkEntity::Rel { id } => view.delete_rel(id),
270                    }
271                    Ok(entity.work())
272                })
273            }
274            TargetsInner::Set { items, factors } => {
275                self.run_row_space(view, targets, factors, cursor, budget, |view, row| {
276                    apply_sets(view, row, items, params, self.cypher_version)
277                })
278            }
279            TargetsInner::Remove { items, factors } => {
280                self.run_row_space(view, targets, factors, cursor, budget, |view, row| {
281                    let resolved = resolve_removes(view, row, items, params, self.cypher_version)?;
282                    apply_resolved_removes(view, resolved)
283                })
284            }
285            TargetsInner::Create { patterns, factors } => {
286                self.run_row_space(view, targets, factors, cursor, budget, |view, row| {
287                    create_patterns(view, row, patterns, params, self.cypher_version)
288                })
289            }
290        }
291    }
292
293    /// The scaffold every row-driven write flavor shares: budgeted walk of
294    /// the factor product, one executed combination per step; only the
295    /// per-row write differs.
296    fn run_row_space(
297        &self,
298        view: &ExecGraph<'_>,
299        targets: &BulkTargets,
300        factors: &[Vec<i64>],
301        cursor: &mut BulkCursor,
302        budget: u64,
303        write: impl Fn(&ExecGraph<'_>, &mut Row) -> Result<()>,
304    ) -> Result<bool> {
305        run_budgeted(view, cursor, targets.total_work(), budget, |combo| {
306            self.execute_combo(view, factors, combo, &write)?;
307            Ok(1)
308        })
309    }
310
311    /// One combination of the factor product: decode the flat index into
312    /// per-factor ids (last factor varies fastest, matching the engine's
313    /// nested-match row order), bind every factor variable to the entity's
314    /// fresh value at this chunk's snapshot, and run the write clause
315    /// through the same per-row logic (`write`) the unbatched dispatch
316    /// uses.
317    fn execute_combo(
318        &self,
319        view: &ExecGraph<'_>,
320        factors: &[Vec<i64>],
321        combo: u64,
322        write: impl FnOnce(&ExecGraph<'_>, &mut Row) -> Result<()>,
323    ) -> Result<()> {
324        let mut row = Row::new();
325        let mut rest = combo;
326        for (factor, ids) in self.factors.iter().zip(factors).rev() {
327            let id = ids[(rest % ids.len() as u64) as usize];
328            rest /= ids.len() as u64;
329            let value = match factor.source {
330                FactorSource::Nodes { .. } => view.node(id).map(Value::from_node),
331                FactorSource::Rels { .. } => view.rel(id).map(Value::from_relationship),
332            };
333            // A concurrently deleted entity voids its combinations: the
334            // optimistic conflict check already rejected overlapping
335            // writes where it can; skipping keeps the target snapshot's
336            // surviving space exact.
337            let Some(value) = value else {
338                return Ok(());
339            };
340            row.insert(factor.var.clone(), value);
341        }
342        write(view, &mut row)
343    }
344}