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)]
26pub(super) enum 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)]
44pub(super) enum 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
73/// The row-space size of a batched write: the product of the factor id
74/// sets — one empty factor empties the whole space (issue 77). The one
75/// spelling both the threshold estimate and the `DELETE` guard read.
76fn factor_space_len(factor_ids: &[Vec<i64>]) -> u64 {
77    factor_ids
78        .iter()
79        .map(|ids| ids.len() as u64)
80        .fold(1u64, u64::saturating_mul)
81}
82
83impl BulkTargets {
84    /// The estimated touched-entity count used against the batching
85    /// threshold: entity count plus incident relationships for `DELETE`,
86    /// the factor product for the row-driven writes.
87    pub fn total_work(&self) -> u64 {
88        match &self.0 {
89            TargetsInner::Delete { entities, .. } => entities
90                .iter()
91                .map(BulkEntity::work)
92                .fold(0u64, u64::saturating_add),
93            TargetsInner::Set { factors, .. }
94            | TargetsInner::Remove { factors, .. }
95            | TargetsInner::Create { factors, .. } => factor_space_len(factors),
96        }
97    }
98}
99
100/// Cursor into the target space: the next entity index (`DELETE`) or
101/// combination index (row-driven writes) to process.
102#[derive(Debug, Default)]
103pub struct BulkCursor {
104    next: u64,
105}
106
107/// The budgeted loop both phase-2 arms share: cancel-check every
108/// [`CANCEL_CHECK_STRIDE`] steps, advance the cursor, accumulate the
109/// work `step` reports, and stop once `budget` work units are spent or
110/// the `total`-sized space is exhausted. Returns `true` when the space
111/// is exhausted.
112fn run_budgeted(
113    view: &ExecGraph<'_>,
114    cursor: &mut BulkCursor,
115    total: u64,
116    budget: u64,
117    mut step: impl FnMut(u64) -> Result<u64>,
118) -> Result<bool> {
119    let mut spent = 0u64;
120    while cursor.next < total {
121        if cursor.next.is_multiple_of(CANCEL_CHECK_STRIDE) {
122            view.check_cancelled()?;
123        }
124        let work = step(cursor.next)?;
125        cursor.next += 1;
126        spent = spent.saturating_add(work);
127        if spent >= budget {
128            break;
129        }
130    }
131    Ok(cursor.next >= total)
132}
133
134impl BulkWrite {
135    /// Phase 1: snapshot the matched entity id space at `snapshot_ts`.
136    /// Returns `Ok(None)` when the catalog holds any constraint: batched
137    /// commits validate per batch, so constrained catalogs keep the
138    /// unbatched atomic path (ADR-0209 §1). A non-`DETACH` node delete
139    /// preflights `DeleteConnectedNode` across every target here, before
140    /// the first batch commits.
141    pub fn collect_targets(&self, graph: &Graph, snapshot_ts: u64) -> Result<Option<BulkTargets>> {
142        if !graph.named_constraints().is_empty() {
143            return Ok(None);
144        }
145        let view = ExecGraph::read_at(graph, snapshot_ts);
146        let mut factors = Vec::with_capacity(self.factors.len());
147        for factor in &self.factors {
148            let ids = match &factor.source {
149                // Labeled/typed factors go through the interned-id
150                // probes; only the untyped/unlabeled factors pay a full
151                // sweep.
152                FactorSource::Nodes { labels } if !labels.is_empty() => {
153                    let mut sets: Vec<Vec<NodeId>> = labels
154                        .iter()
155                        .map(|label| graph.node_ids_with_label_at(label, snapshot_ts))
156                        .collect();
157                    sets.sort_by_key(Vec::len);
158                    let (smallest, rest) = sets.split_first().expect("non-empty labels");
159                    let rest: Vec<HashSet<NodeId>> = rest
160                        .iter()
161                        .map(|ids| ids.iter().copied().collect())
162                        .collect();
163                    smallest
164                        .iter()
165                        .copied()
166                        .filter(|id| rest.iter().all(|set| set.contains(id)))
167                        .collect()
168                }
169                FactorSource::Nodes { .. } => view.all_node_ids(),
170                FactorSource::Rels { types } if !types.is_empty() => {
171                    let mut ids: Vec<RelId> = types
172                        .iter()
173                        .flat_map(|rel_type| graph.rel_ids_of_type_at(rel_type, snapshot_ts))
174                        .collect();
175                    ids.sort_unstable();
176                    ids.dedup();
177                    ids
178                }
179                FactorSource::Rels { .. } => view.all_rel_ids(),
180            };
181            factors.push(ids);
182        }
183        let inner = match &self.kind {
184            BulkKind::Delete { detach, targets } => {
185                self.collect_delete_targets(&view, *detach, targets, &factors)?
186            }
187            BulkKind::Set { items } => TargetsInner::Set {
188                items: items.clone(),
189                factors,
190            },
191            BulkKind::Remove { items } => TargetsInner::Remove {
192                items: items.clone(),
193                factors,
194            },
195            BulkKind::Create { patterns } => TargetsInner::Create {
196                patterns: patterns.clone(),
197                factors,
198            },
199        };
200        Ok(Some(BulkTargets(inner)))
201    }
202
203    /// The `DELETE` target space: gather the ids of the factors the
204    /// `DELETE` names (deduplicated across the possibly cross-product
205    /// row space — deleting an entity is idempotent, so each id is
206    /// processed once), preflight `DeleteConnectedNode` for a
207    /// non-`DETACH` delete, and estimate each entity's work.
208    pub(super) fn collect_delete_targets(
209        &self,
210        view: &ExecGraph<'_>,
211        detach: bool,
212        targets: &HashSet<String>,
213        factor_ids: &[Vec<i64>],
214    ) -> Result<TargetsInner> {
215        let mut node_ids: Vec<NodeId> = Vec::new();
216        let mut rel_ids: Vec<RelId> = Vec::new();
217        // The row space is the cross product of ALL factors, named or
218        // not: one empty factor empties it, so the DELETE deletes
219        // nothing (issue 77) — the same `factor_space_len` product the
220        // row-driven arms' `total_work` charges (the DELETE arm sums
221        // entity work and never sees the row space, so this guard is
222        // the empty-factor fact's one home on this path).
223        if factor_space_len(factor_ids) == 0 {
224            return Ok(TargetsInner::Delete {
225                detach,
226                entities: Vec::new(),
227            });
228        }
229        // The ids are positional, one list per factor in `self.factors`
230        // order (built by `collect_targets`); state the pairing once so
231        // a disagreeing caller fails loudly instead of `zip` truncating
232        // to the shorter side.
233        assert_eq!(
234            self.factors.len(),
235            factor_ids.len(),
236            "bulk DELETE pairs each factor with exactly one id list: {} factors, {} id lists",
237            self.factors.len(),
238            factor_ids.len(),
239        );
240        for (factor, ids) in self.factors.iter().zip(factor_ids) {
241            if !targets.contains(&factor.var) {
242                continue;
243            }
244            match factor.source {
245                FactorSource::Nodes { .. } => node_ids.extend_from_slice(ids),
246                FactorSource::Rels { .. } => rel_ids.extend_from_slice(ids),
247            }
248        }
249        node_ids.sort_unstable();
250        node_ids.dedup();
251        rel_ids.sort_unstable();
252        rel_ids.dedup();
253        if !detach {
254            // Preflight the DeleteConnectedNode error before the first
255            // batch commits, keeping the statement atomic for this error
256            // while no concurrent writer adds a relationship after this
257            // snapshot.
258            for &id in &node_ids {
259                // The probe's predicate is infallible; an error that
260                // ever becomes constructible must fail loudly, not
261                // read as "no neighbor" — which would delete a
262                // connected node as if it had none.
263                let hit = view
264                    .try_find_neighbor(id, Direction::Both, &[], |_| Ok::<bool, ()>(true))
265                    .expect("the neighbor probe's predicate is infallible");
266                if hit.is_some() {
267                    return Err(crate::graph::delete_connected_node_error());
268                }
269            }
270        }
271        let mut entities = Vec::with_capacity(node_ids.len() + rel_ids.len());
272        for id in node_ids {
273            let work = if detach {
274                1u64.saturating_add(view.adj_len(id, Direction::Both) as u64)
275            } else {
276                1
277            };
278            entities.push(BulkEntity::Node { id, work });
279        }
280        entities.extend(rel_ids.into_iter().map(|id| BulkEntity::Rel { id }));
281        Ok(TargetsInner::Delete { detach, entities })
282    }
283
284    /// Phase 2: apply up to `budget` work units starting at `cursor` on
285    /// the caller's write view (which carries the cancellation token).
286    /// Returns `true` when the target space is exhausted. The caller
287    /// commits the view's scratch per chunk.
288    pub fn execute_chunk(
289        &self,
290        view: &ExecGraph<'_>,
291        targets: &BulkTargets,
292        cursor: &mut BulkCursor,
293        budget: u64,
294        params: &BTreeMap<String, Value>,
295    ) -> Result<bool> {
296        match &targets.0 {
297            TargetsInner::Delete { detach, entities } => {
298                let detach = *detach;
299                run_budgeted(view, cursor, entities.len() as u64, budget, |i| {
300                    let entity = entities[i as usize];
301                    match entity {
302                        BulkEntity::Node { id, .. } => view.delete_node(id, detach)?,
303                        BulkEntity::Rel { id } => view.delete_rel(id),
304                    }
305                    Ok(entity.work())
306                })
307            }
308            TargetsInner::Set { items, factors } => {
309                self.run_row_space(view, targets, factors, cursor, budget, |view, row| {
310                    apply_sets(view, row, items, params)
311                })
312            }
313            TargetsInner::Remove { items, factors } => {
314                self.run_row_space(view, targets, factors, cursor, budget, |view, row| {
315                    let resolved = resolve_removes(view, row, items, params)?;
316                    apply_resolved_removes(view, resolved)
317                })
318            }
319            TargetsInner::Create { patterns, factors } => {
320                self.run_row_space(view, targets, factors, cursor, budget, |view, row| {
321                    create_patterns(view, row, patterns, params)
322                })
323            }
324        }
325    }
326
327    /// The scaffold every row-driven write flavor shares: budgeted walk of
328    /// the factor product, one executed combination per step; only the
329    /// per-row write differs.
330    fn run_row_space(
331        &self,
332        view: &ExecGraph<'_>,
333        targets: &BulkTargets,
334        factors: &[Vec<i64>],
335        cursor: &mut BulkCursor,
336        budget: u64,
337        write: impl Fn(&ExecGraph<'_>, &mut Row) -> Result<()>,
338    ) -> Result<bool> {
339        run_budgeted(view, cursor, targets.total_work(), budget, |combo| {
340            self.execute_combo(view, factors, combo, &write)?;
341            Ok(1)
342        })
343    }
344
345    /// One combination of the factor product: decode the flat index into
346    /// per-factor ids (last factor varies fastest, matching the engine's
347    /// nested-match row order), bind every factor variable to the entity's
348    /// fresh value at this chunk's snapshot, and run the write clause
349    /// through the same per-row logic (`write`) the unbatched dispatch
350    /// uses.
351    fn execute_combo(
352        &self,
353        view: &ExecGraph<'_>,
354        factors: &[Vec<i64>],
355        combo: u64,
356        write: impl FnOnce(&ExecGraph<'_>, &mut Row) -> Result<()>,
357    ) -> Result<()> {
358        let mut row = Row::new();
359        let mut rest = combo;
360        for (factor, ids) in self.factors.iter().zip(factors).rev() {
361            let id = ids[(rest % ids.len() as u64) as usize];
362            rest /= ids.len() as u64;
363            let value = match factor.source {
364                FactorSource::Nodes { .. } => view.node(id).map(Value::from_node),
365                FactorSource::Rels { .. } => view.rel(id).map(Value::from_relationship),
366            };
367            // A concurrently deleted entity voids its combinations: the
368            // optimistic conflict check already rejected overlapping
369            // writes where it can; skipping keeps the target snapshot's
370            // surviving space exact.
371            let Some(value) = value else {
372                return Ok(());
373            };
374            row.insert(factor.var.clone(), value);
375        }
376        write(view, &mut row)
377    }
378}