relate_executor/exec/bulk/
run.rs1use 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
18const CANCEL_CHECK_STRIDE: u64 = 1024;
21
22#[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#[derive(Debug)]
44enum TargetsInner {
45 Delete {
47 detach: bool,
48 entities: Vec<BulkEntity>,
49 },
50 Set {
53 items: Vec<relate_ir::SetItem>,
54 factors: Vec<Vec<i64>>,
55 },
56 Remove {
58 items: Vec<relate_ir::RemoveItem>,
59 factors: Vec<Vec<i64>>,
60 },
61 Create {
63 patterns: Vec<relate_ir::PathPattern>,
64 factors: Vec<Vec<i64>>,
65 },
66}
67
68#[derive(Debug)]
71pub struct BulkTargets(TargetsInner);
72
73impl BulkTargets {
74 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#[derive(Debug, Default)]
96pub struct BulkCursor {
97 next: u64,
98}
99
100fn 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 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 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 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 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 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)
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)?;
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)
288 })
289 }
290 }
291 }
292
293 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 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 let Some(value) = value else {
338 return Ok(());
339 };
340 row.insert(factor.var.clone(), value);
341 }
342 write(view, &mut row)
343 }
344}