1use super::execution_context::current_connection_id;
22use super::*;
23
24thread_local! {
25 static DEFERRED_UPDATES: std::cell::RefCell<Option<Vec<DeferredUpdate>>> = const { std::cell::RefCell::new(None) };
26 static GRAPH_INSERT_WRITER: std::cell::Cell<Option<(usize, u64, u64)>> = const { std::cell::Cell::new(None) };
27 static DML_CAPTURE_OWNER: std::cell::Cell<Option<(usize, u64, bool)>> = const { std::cell::Cell::new(None) };
28 static DML_CAPTURE_GRAPH_WRITER: std::cell::RefCell<Option<GraphInsertWriter>> = const { std::cell::RefCell::new(None) };
29 static CHUNKS_CHECKPOINT_BY_VOLUME: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
30}
31
32struct GraphInsertWriter {
33 manager: std::sync::Arc<crate::storage::transaction::snapshot::SnapshotManager>,
34 xid: u64,
35 finished: bool,
36}
37
38impl GraphInsertWriter {
39 fn begin(runtime: &RedDBRuntime) -> Self {
40 let manager = runtime.snapshot_manager();
41 let xid = manager.begin();
42 let identity = std::sync::Arc::as_ptr(&runtime.inner) as usize;
43 GRAPH_INSERT_WRITER.with(|slot| {
44 assert!(slot
45 .replace(Some((identity, current_connection_id(), xid)))
46 .is_none());
47 });
48 Self {
49 manager,
50 xid,
51 finished: false,
52 }
53 }
54
55 fn commit(&mut self) {
56 self.manager.commit(self.xid);
57 self.finished = true;
58 }
59}
60
61impl Drop for GraphInsertWriter {
62 fn drop(&mut self) {
63 GRAPH_INSERT_WRITER.with(|slot| slot.set(None));
64 if !self.finished {
65 self.manager.rollback(self.xid);
66 }
67 }
68}
69
70struct DeferredUpdate {
71 runtime: RedDBRuntime,
72 collection: String,
73 old_id: EntityId,
74 new_id: EntityId,
75 previous_xmax: u64,
76 update: Arc<crate::application::entity::AutocommitUpdate>,
77 committed: bool,
78}
79
80impl Drop for DeferredUpdate {
81 fn drop(&mut self) {
82 if !self.committed {
83 let topology = self
84 .runtime
85 .index_store_ref()
86 .collection_topology_lock(&self.collection);
87 if let Err(error) = self.runtime.revive_versioned_update(
88 &self.collection,
89 self.old_id,
90 self.new_id,
91 self.update.xid,
92 self.previous_xmax,
93 topology.read_recursive(),
94 ) {
95 tracing::error!(%error, "autocommit update rollback failed");
96 }
97 }
98 }
99}
100
101struct DeferredUpdates;
102
103struct RowVersion {
105 id: crate::storage::unified::entity::EntityId,
106 xmin: crate::storage::transaction::snapshot::Xid,
107 xmax: crate::storage::transaction::snapshot::Xid,
108 branch_origin: Option<u64>,
109}
110
111#[cfg(test)]
112thread_local! {
113 pub(crate) static COMMIT_CONFLICT_WALKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
116}
117
118type WrittenRowVersions =
120 HashMap<String, HashMap<crate::storage::unified::entity::EntityId, Vec<RowVersion>>>;
121
122impl DeferredUpdates {
123 fn begin() -> Self {
124 DEFERRED_UPDATES.with(|slot| {
125 assert!(slot.borrow().is_none(), "update WAL scopes cannot nest");
126 *slot.borrow_mut() = Some(Vec::new());
127 });
128 Self
129 }
130
131 fn commit(self) {
132 DEFERRED_UPDATES.with(|slot| {
133 for mut pending in slot.borrow_mut().take().expect("update WAL scope") {
134 let update = &pending.update;
135 update.commit();
136 pending.committed = true;
137 }
138 });
139 }
140
141 fn prepare(&self) -> RedDBResult<()> {
142 DEFERRED_UPDATES.with(|slot| {
143 for pending in slot.borrow().as_ref().expect("update WAL scope") {
144 let store = pending.runtime.db().store();
145 let Some(manager) = store.get_collection(&pending.collection) else {
146 return Err(RedDBError::Internal(
147 "updated collection disappeared".into(),
148 ));
149 };
150 let epoch = manager
151 .try_get(pending.new_id, usize::MAX)?
152 .and_then(|entity| entity.branch_version().map(|version| version.origin));
153 let old_owned = manager
154 .try_get(pending.old_id, usize::MAX)
155 .map_err(|error| RedDBError::Internal(error.to_string()))?
156 .is_some_and(|old| {
157 epoch.map_or(old.xmax, |epoch| old.branch_xmax(epoch)) == pending.update.xid
158 });
159 let new_owned = manager
160 .try_get(pending.new_id, usize::MAX)
161 .map_err(|error| RedDBError::Internal(error.to_string()))?
162 .is_some_and(|new| new.xmin == pending.update.xid);
163 if !old_owned || !new_owned {
164 return Err(RedDBRuntime::conflict_error(
165 &pending.collection,
166 pending.old_id,
167 pending.update.xid,
168 ));
169 }
170 }
171 Ok(())
172 })
173 }
174}
175
176impl Drop for DeferredUpdates {
177 fn drop(&mut self) {
178 let pending = DEFERRED_UPDATES.with(|slot| slot.borrow_mut().take());
179 if let Some(pending) = pending {
180 for update in pending.into_iter().rev() {
181 drop(update);
182 }
183 }
184 }
185}
186
187pub(crate) fn autocommit_update_capture_available() -> bool {
188 DEFERRED_UPDATES.with(|slot| slot.borrow().is_some())
189}
190
191pub(crate) fn publish_autocommit_update(
192 runtime: &RedDBRuntime,
193 item: &crate::application::entity::AppliedEntityMutation,
194 update: &Arc<crate::application::entity::AutocommitUpdate>,
195) {
196 if UnifiedStore::deferred_store_wal_capture_active() {
197 DEFERRED_UPDATES.with(|slot| {
198 slot.borrow_mut()
199 .as_mut()
200 .expect("update WAL scope")
201 .push(DeferredUpdate {
202 runtime: runtime.clone(),
203 collection: item.collection.clone(),
204 old_id: item.replaced_entity.as_ref().expect("versioned update").id,
205 new_id: item.entity.id,
206 previous_xmax: item.replaced_entity_previous_xmax,
207 update: Arc::clone(update),
208 committed: false,
209 });
210 });
211 } else {
212 update.commit();
213 }
214}
215
216struct DmlWalCapture(bool);
218
219struct CapturedDmlWal {
220 actions: crate::storage::unified::DeferredStoreWalActions,
221 graph_writer: Option<GraphInsertWriter>,
222}
223
224impl DmlWalCapture {
225 fn begin(runtime: &RedDBRuntime, transactional: bool) -> Self {
226 assert!(
227 !UnifiedStore::deferred_store_wal_capture_active(),
228 "DML WAL captures cannot nest"
229 );
230 let identity = std::sync::Arc::as_ptr(&runtime.inner) as usize;
231 DML_CAPTURE_OWNER.with(|slot| {
232 assert!(slot
233 .replace(Some((identity, current_connection_id(), transactional)))
234 .is_none());
235 });
236 UnifiedStore::begin_deferred_store_wal_capture();
237 Self(true)
238 }
239
240 fn finish(mut self) -> CapturedDmlWal {
241 self.0 = false;
242 DML_CAPTURE_OWNER.with(|slot| slot.set(None));
243 CapturedDmlWal {
244 actions: UnifiedStore::take_deferred_store_wal_capture(),
245 graph_writer: DML_CAPTURE_GRAPH_WRITER.with(|slot| slot.borrow_mut().take()),
246 }
247 }
248}
249
250impl Drop for DmlWalCapture {
251 fn drop(&mut self) {
252 if self.0 {
253 DML_CAPTURE_OWNER.with(|slot| slot.set(None));
254 let _ = UnifiedStore::take_deferred_store_wal_capture();
255 DML_CAPTURE_GRAPH_WRITER.with(|slot| drop(slot.borrow_mut().take()));
256 }
257 }
258}
259
260impl RedDBRuntime {
261 pub(super) fn vcs_state_write_snapshot(
264 &self,
265 collection: &str,
266 ) -> RedDBResult<(
267 super::execution_context::SnapshotContext,
268 crate::storage::transaction::snapshot::SnapshotRetentionGuard,
269 )> {
270 self.vcs_writer_epoch(collection)?;
271 let (mut context, retention) = self.native_read_snapshot()?;
272 if self.current_xid().is_none() {
273 context.snapshot = self.snapshot_manager().fresh_read_snapshot();
274 context.branch = self.vcs_branch_read_view(&context.snapshot, None)?;
275 }
276 Ok((context, retention))
277 }
278
279 pub(crate) fn insert_vcs_state_version(
282 &self,
283 collection: &str,
284 mut entity: UnifiedEntity,
285 previous: Option<EntityId>,
286 ) -> RedDBResult<EntityId> {
287 let store = self.db().store();
288 let epoch = self.vcs_writer_epoch(collection)?.ok_or_else(|| {
289 RedDBError::InvalidOperation("state version requires a versioned collection".into())
290 })?;
291 let xid = self
292 .current_xid()
293 .or_else(|| self.graph_insert_xid())
294 .ok_or_else(|| {
295 RedDBError::InvalidOperation("state version requires a WAL writer".into())
296 })?;
297 entity.id = store.next_entity_id();
298 entity.set_xmin(xid);
299 entity.set_xmax(0);
300 entity.clear_branch_version();
301 entity.set_branch_origin(epoch);
302 let id = entity.id;
303 if let Some(previous) = previous {
304 let mut old = store
305 .try_get(collection, previous, usize::MAX)?
306 .ok_or_else(|| RedDBError::NotFound(previous.to_string()))?;
307 entity.set_logical_id(old.logical_id());
308 if let (
309 crate::storage::EntityKind::TableRow {
310 row_id: destination,
311 ..
312 },
313 crate::storage::EntityKind::TableRow { row_id: source, .. },
314 ) = (&mut entity.kind, &old.kind)
315 {
316 *destination = *source;
317 }
318 let previous_xmax = old.branch_xmax(epoch);
319 old.set_branch_xmax(epoch, xid);
320 store.install_versioned_table_row_update(collection, old, entity, None)?;
321 if self.current_xid().is_some() {
322 self.record_pending_versioned_update(
323 current_connection_id(),
324 collection,
325 previous,
326 id,
327 xid,
328 previous_xmax,
329 );
330 }
331 } else {
332 store.insert_auto(collection, entity)?;
333 }
334 Ok(id)
335 }
336
337 pub(crate) fn graph_insert_xid(&self) -> Option<u64> {
338 let identity = std::sync::Arc::as_ptr(&self.inner) as usize;
339 GRAPH_INSERT_WRITER.with(|slot| {
340 slot.get().and_then(|(owner, conn, xid)| {
341 (owner == identity && conn == current_connection_id()).then_some(xid)
342 })
343 })
344 }
345
346 pub(crate) fn with_versioned_graph_insert<T>(
348 &self,
349 f: impl FnOnce() -> RedDBResult<T>,
350 ) -> RedDBResult<T> {
351 let identity = std::sync::Arc::as_ptr(&self.inner) as usize;
352 let connection_id = current_connection_id();
353 if self.current_xid().is_some() {
354 if UnifiedStore::deferred_store_wal_capture_active() {
355 if DML_CAPTURE_OWNER.with(|slot| slot.get())
356 == Some((identity, connection_id, true))
357 {
358 return f();
359 }
360 return Err(RedDBError::InvalidOperation(
361 "versioned entity insertion cannot join an unrelated WAL capture".to_string(),
362 ));
363 }
364 return self.with_deferred_store_wal_if_transaction(f);
365 }
366 if self.graph_insert_xid().is_some() {
367 return f();
368 }
369 if UnifiedStore::deferred_store_wal_capture_active() {
370 if DML_CAPTURE_OWNER.with(|slot| slot.get()) != Some((identity, connection_id, false))
371 || GRAPH_INSERT_WRITER.with(|slot| slot.get().is_some())
372 {
373 return Err(RedDBError::InvalidOperation(
374 "versioned entity insertion cannot join an unrelated WAL capture".to_string(),
375 ));
376 }
377 let writer = GraphInsertWriter::begin(self);
378 let result = f();
379 DML_CAPTURE_GRAPH_WRITER.with(|slot| {
380 assert!(slot.borrow_mut().replace(writer).is_none());
381 });
382 return result;
383 }
384 self.checkpoint_before_statement()?;
385 let deletions = super::delete_publication::DeletePublicationScope::begin();
386 let updates = DeferredUpdates::begin();
387 let mut writer = GraphInsertWriter::begin(self);
388 let capture = DmlWalCapture::begin(self, false);
389 let result = f();
390 let CapturedDmlWal {
391 actions,
392 mut graph_writer,
393 } = capture.finish();
394 if result.is_err() {
395 self.flush_deferred_cache_invalidation();
396 return result;
397 }
398 let published = deletions.publish(self, || {
399 updates.prepare()?;
400 self.inner
401 .db
402 .store()
403 .append_deferred_store_wal_actions(actions)
404 .map_err(|err| RedDBError::Internal(err.to_string()))?;
405 if let Some(writer) = &mut graph_writer {
406 writer.commit();
407 }
408 writer.commit();
409 updates.commit();
410 Ok(())
411 });
412 self.flush_deferred_cache_invalidation();
413 published?;
414 result
415 }
416
417 pub(crate) fn with_graph_insert_for_dml<T>(
418 &self,
419 query: &InsertQuery,
420 f: impl FnOnce() -> RedDBResult<T>,
421 ) -> RedDBResult<T> {
422 if matches!(
423 query.entity_type,
424 InsertEntityType::Node
425 | InsertEntityType::Edge
426 | InsertEntityType::Vector
427 | InsertEntityType::Document
428 ) && (self.vcs_is_versioned(&query.table)? || self.has_graph_contract(&query.table))
429 {
430 self.with_versioned_graph_insert(f)
431 } else {
432 self.with_deferred_store_wal_for_dml(self.insert_may_emit_events(query), f)
433 }
434 }
435
436 pub(crate) fn rollback_connection(
437 &self,
438 connection_id: u64,
439 ) -> RedDBResult<Option<crate::storage::transaction::snapshot::TxnContext>> {
440 let undo = self.revive_pending_versioned_updates(connection_id);
444 self.revive_pending_tombstones(connection_id);
445 let context = self.inner.transaction_state.rollback(connection_id);
446 self.discard_pending_queue_dedup(connection_id);
447 self.discard_pending_kv_watch_events(connection_id);
448 self.discard_pending_queue_wakes(connection_id);
449 self.discard_pending_store_wal_actions(connection_id);
450 self.release_pending_claim_locks(connection_id);
451 self.discard_pending_vault_writes(connection_id)?;
452 undo?;
453 Ok(context)
454 }
455
456 pub(crate) fn record_pending_tombstone(
462 &self,
463 conn_id: u64,
464 collection: &str,
465 id: crate::storage::unified::entity::EntityId,
466 stamper_xid: crate::storage::transaction::snapshot::Xid,
467 previous_xmax: crate::storage::transaction::snapshot::Xid,
468 branch_epoch: Option<u64>,
469 ) {
470 self.inner
471 .pending_tombstones
472 .write()
473 .entry(conn_id)
474 .or_default()
475 .push((
476 collection.to_string(),
477 id,
478 stamper_xid,
479 previous_xmax,
480 branch_epoch,
481 ));
482 }
483
484 pub(crate) fn record_pending_versioned_update(
485 &self,
486 conn_id: u64,
487 collection: &str,
488 old_id: crate::storage::unified::entity::EntityId,
489 new_id: crate::storage::unified::entity::EntityId,
490 stamper_xid: crate::storage::transaction::snapshot::Xid,
491 previous_xmax: crate::storage::transaction::snapshot::Xid,
492 ) {
493 self.inner
494 .pending_versioned_updates
495 .write()
496 .entry(conn_id)
497 .or_default()
498 .push((
499 collection.to_string(),
500 old_id,
501 new_id,
502 stamper_xid,
503 previous_xmax,
504 ));
505 }
506
507 pub(crate) fn record_pending_queue_dedup(
508 &self,
509 conn_id: u64,
510 queue: &str,
511 dedup_key: &str,
512 metadata_id: crate::storage::unified::entity::EntityId,
513 ) {
514 self.inner
515 .pending_queue_dedup
516 .write()
517 .entry(conn_id)
518 .or_default()
519 .push((queue.to_string(), dedup_key.to_string(), metadata_id));
520 }
521
522 pub(crate) fn with_deferred_store_wal_if_transaction<T>(
523 &self,
524 f: impl FnOnce() -> RedDBResult<T>,
525 ) -> RedDBResult<T> {
526 let conn_id = current_connection_id();
527 if !self.inner.transaction_state.in_transaction(conn_id) {
528 return f();
529 }
530
531 let logical_start = self
532 .inner
533 .pending_logical_records
534 .lock()
535 .get(&conn_id)
536 .map_or(0, |pending| pending.len());
537 let capture = DmlWalCapture::begin(self, true);
538 let result = f();
539 let CapturedDmlWal {
540 actions,
541 graph_writer,
542 } = capture.finish();
543 if graph_writer.is_some() {
544 return Err(RedDBError::InvalidOperation(
545 "autocommit graph writer cannot join a transaction WAL capture".to_string(),
546 ));
547 }
548 self.flush_deferred_cache_invalidation();
549 match result {
550 Ok(value) => {
551 self.record_pending_store_wal_actions(conn_id, actions);
552 Ok(value)
553 }
554 Err(err) => {
555 if let Some(records) = self.inner.pending_logical_records.lock().get_mut(&conn_id) {
556 records.truncate(logical_start);
557 }
558 Err(err)
559 }
560 }
561 }
562
563 pub(crate) fn with_deferred_store_wal_for_dml<T>(
564 &self,
565 capture_autocommit_events: bool,
566 f: impl FnOnce() -> RedDBResult<T>,
567 ) -> RedDBResult<T> {
568 self.with_deferred_store_wal(capture_autocommit_events, true, f)
569 }
570
571 pub(crate) fn with_deferred_store_wal_for_dml_chunk<T>(
576 &self,
577 f: impl FnOnce() -> RedDBResult<T>,
578 ) -> RedDBResult<T> {
579 let by_volume = CHUNKS_CHECKPOINT_BY_VOLUME.with(|allowed| allowed.get());
580 self.with_deferred_store_wal(true, by_volume, f)
581 }
582
583 pub(crate) fn chunk_checkpoints_for(&self, collection: &str, rows: usize) -> ChunkCheckpoints {
586 let allowed = self
587 .inner
588 .db
589 .store()
590 .chunks_checkpoint_by_volume(collection, rows);
591 ChunkCheckpoints(CHUNKS_CHECKPOINT_BY_VOLUME.with(|slot| slot.replace(allowed)))
592 }
593
594 fn with_deferred_store_wal<T>(
595 &self,
596 capture_autocommit_events: bool,
597 by_volume: bool,
598 f: impl FnOnce() -> RedDBResult<T>,
599 ) -> RedDBResult<T> {
600 let conn_id = current_connection_id();
601 if self.inner.transaction_state.in_transaction(conn_id) {
602 return self.with_deferred_store_wal_if_transaction(f);
603 }
604 if by_volume {
605 self.checkpoint_before_statement()?;
606 } else {
607 self.drain_committed_writes_under_pressure(0)?;
608 }
609 if !capture_autocommit_events {
610 return f();
611 }
612
613 let deletions = super::delete_publication::DeletePublicationScope::begin();
614 let updates = DeferredUpdates::begin();
615 let capture = DmlWalCapture::begin(self, false);
616 let result = f();
617 let CapturedDmlWal {
618 actions,
619 mut graph_writer,
620 } = capture.finish();
621 if result.is_err() && (deletions.has_pending() || graph_writer.is_some()) {
622 self.flush_deferred_cache_invalidation();
623 return result;
624 }
625 let published = deletions.publish(self, || {
626 updates.prepare()?;
627 self.inner
628 .db
629 .store()
630 .append_deferred_store_wal_actions(actions)
631 .map_err(|err| RedDBError::Internal(err.to_string()))?;
632 if let Some(writer) = &mut graph_writer {
633 writer.commit();
634 }
635 updates.commit();
636 Ok(())
637 });
638 self.flush_deferred_cache_invalidation();
639 published?;
640 result
641 }
642
643 pub(crate) fn insert_may_emit_events(&self, query: &InsertQuery) -> bool {
644 !query.suppress_events
645 && self.collection_has_event_subscriptions_for_operation(
646 &query.table,
647 crate::catalog::SubscriptionOperation::Insert,
648 )
649 }
650
651 pub(crate) fn update_may_emit_events(&self, query: &UpdateQuery) -> bool {
652 !query.suppress_events
653 && self.collection_has_event_subscriptions_for_operation(
654 &query.table,
655 crate::catalog::SubscriptionOperation::Update,
656 )
657 }
658
659 pub(crate) fn delete_may_emit_events(&self, query: &DeleteQuery) -> bool {
660 !query.suppress_events
661 && self.collection_has_event_subscriptions_for_operation(
662 &query.table,
663 crate::catalog::SubscriptionOperation::Delete,
664 )
665 }
666
667 fn collection_has_event_subscriptions_for_operation(
668 &self,
669 collection: &str,
670 operation: crate::catalog::SubscriptionOperation,
671 ) -> bool {
672 let Some(contract) = self.db().collection_contract_arc(collection) else {
673 return false;
674 };
675 contract.subscriptions.iter().any(|subscription| {
676 subscription.enabled
677 && (subscription.ops_filter.is_empty()
678 || subscription.ops_filter.contains(&operation))
679 })
680 }
681
682 pub(crate) fn record_pending_store_wal_actions(
683 &self,
684 conn_id: u64,
685 actions: crate::storage::unified::DeferredStoreWalActions,
686 ) {
687 if actions.is_empty() {
688 return;
689 }
690 let mut guard = self.inner.pending_store_wal_actions.write();
691 guard
692 .entry(conn_id)
693 .or_default()
694 .push((self.current_xid().unwrap_or(0), actions));
695 }
696
697 pub(crate) fn flush_pending_store_wal_actions(&self, conn_id: u64) -> RedDBResult<()> {
698 let groups = self
699 .inner
700 .pending_store_wal_actions
701 .write()
702 .remove(&conn_id)
703 .unwrap_or_default();
704 let mut actions = crate::storage::unified::DeferredStoreWalActions::default();
705 for (xid, group) in groups {
706 if !self.snapshot_manager().is_aborted(xid) {
707 actions.extend(group);
708 }
709 }
710 self.commit_transactional_replication(conn_id, actions)
711 }
712
713 pub(crate) fn discard_pending_store_wal_actions(&self, conn_id: u64) {
714 self.inner.pending_commit_policies.lock().remove(&conn_id);
715 self.inner.pending_logical_records.lock().remove(&conn_id);
716 self.inner
717 .pending_store_wal_actions
718 .write()
719 .remove(&conn_id);
720 }
721
722 fn xid_conflicts_with_snapshot(
723 &self,
724 xid: crate::storage::transaction::snapshot::Xid,
725 snapshot: &crate::storage::transaction::snapshot::Snapshot,
726 own_xids: &std::collections::HashSet<crate::storage::transaction::snapshot::Xid>,
727 ) -> bool {
728 xid != 0
729 && !own_xids.contains(&xid)
730 && !self
731 .inner
732 .transaction_state
733 .snapshot_manager()
734 .is_aborted(xid)
735 && !self
736 .inner
737 .transaction_state
738 .snapshot_manager()
739 .is_active(xid)
740 && (xid > snapshot.xid || snapshot.in_progress.contains(&xid))
741 }
742
743 pub(super) fn conflict_error(
744 collection: &str,
745 logical_id: crate::storage::unified::entity::EntityId,
746 xid: crate::storage::transaction::snapshot::Xid,
747 ) -> RedDBError {
748 RedDBError::Query(format!(
749 "serialization conflict: table row {collection}/{} was modified by concurrent transaction {xid}",
750 logical_id.raw()
751 ))
752 }
753
754 fn written_row_versions<'a>(
759 &self,
760 written: impl Iterator<Item = (&'a str, crate::storage::unified::entity::EntityId)>,
761 ) -> WrittenRowVersions {
762 let mut rows = HashMap::<&str, HashSet<crate::storage::unified::entity::EntityId>>::new();
763 for (collection, logical_id) in written {
764 rows.entry(collection).or_default().insert(logical_id);
765 }
766 let store = self.inner.db.store();
767 let mut versions = WrittenRowVersions::new();
768 for (collection, rows) in rows {
769 let Some(manager) = store.get_collection(collection) else {
770 continue;
771 };
772 #[cfg(test)]
773 COMMIT_CONFLICT_WALKS.with(|walks| walks.set(walks.get() + 1));
774 let of_collection = versions.entry(collection.to_string()).or_default();
775 for candidate in manager.query_all(|entity| rows.contains(&entity.logical_id())) {
776 of_collection
777 .entry(candidate.logical_id())
778 .or_default()
779 .push(RowVersion {
780 id: candidate.id,
781 xmin: candidate.xmin,
782 xmax: candidate.xmax,
783 branch_origin: candidate.branch_version().map(|version| version.origin),
784 });
785 }
786 }
787 versions
788 }
789
790 #[allow(clippy::too_many_arguments)]
791 fn check_logical_row_conflict(
792 &self,
793 collection: &str,
794 logical_id: crate::storage::unified::entity::EntityId,
795 excluded_ids: &[crate::storage::unified::entity::EntityId],
796 versions: &WrittenRowVersions,
797 snapshot: &crate::storage::transaction::snapshot::Snapshot,
798 own_xids: &std::collections::HashSet<crate::storage::transaction::snapshot::Xid>,
799 branch_epoch: Option<u64>,
800 ) -> RedDBResult<()> {
801 let candidates = versions
802 .get(collection)
803 .and_then(|rows| rows.get(&logical_id))
804 .map_or(&[][..], Vec::as_slice);
805 for candidate in candidates {
806 if let Some(epoch) = branch_epoch {
807 if candidate
808 .branch_origin
809 .is_some_and(|origin| origin != epoch)
810 {
811 continue;
812 }
813 }
814 if excluded_ids.contains(&candidate.id) {
815 continue;
816 }
817 if self.xid_conflicts_with_snapshot(candidate.xmin, snapshot, own_xids) {
818 return Err(Self::conflict_error(collection, logical_id, candidate.xmin));
819 }
820 if self.xid_conflicts_with_snapshot(candidate.xmax, snapshot, own_xids) {
821 return Err(Self::conflict_error(collection, logical_id, candidate.xmax));
822 }
823 }
824 Ok(())
825 }
826
827 pub(crate) fn check_table_row_write_conflicts(
828 &self,
829 conn_id: u64,
830 snapshot: &crate::storage::transaction::snapshot::Snapshot,
831 own_xids: &std::collections::HashSet<crate::storage::transaction::snapshot::Xid>,
832 isolation: crate::storage::transaction::IsolationLevel,
833 ) -> RedDBResult<()> {
834 let versioned_updates = self
835 .inner
836 .pending_versioned_updates
837 .read()
838 .get(&conn_id)
839 .cloned()
840 .unwrap_or_default();
841 let tombstones = self
842 .inner
843 .pending_tombstones
844 .read()
845 .get(&conn_id)
846 .cloned()
847 .unwrap_or_default();
848
849 let mut serializable_write_set = std::collections::HashSet::new();
850 let store = self.inner.db.store();
851 let versioned_updates = versioned_updates
854 .into_iter()
855 .filter_map(|(collection, old_id, new_id, xid, previous_xmax)| {
856 let manager = store.get_collection(&collection)?;
857 let old = manager.get(old_id)?;
858 let epoch = manager
859 .get(new_id)
860 .and_then(|entity| entity.branch_version().map(|version| version.origin));
861 let old_xmax = epoch.map_or(old.xmax, |epoch| old.branch_xmax(epoch));
862 Some((
863 collection,
864 old.logical_id(),
865 old_id,
866 new_id,
867 xid,
868 previous_xmax,
869 old_xmax,
870 epoch,
871 ))
872 })
873 .collect::<Vec<_>>();
874 let tombstones = tombstones
875 .into_iter()
876 .filter_map(|(collection, id, xid, previous_xmax, epoch)| {
877 let entity = store.get_collection(&collection)?.get(id)?;
878 let xmax = epoch.map_or(entity.xmax, |epoch| entity.branch_xmax(epoch));
879 Some((
880 collection,
881 entity.logical_id(),
882 id,
883 xid,
884 previous_xmax,
885 xmax,
886 epoch,
887 ))
888 })
889 .collect::<Vec<_>>();
890 let versions = self.written_row_versions(
891 versioned_updates
892 .iter()
893 .map(|update| (update.0.as_str(), update.1))
894 .chain(
895 tombstones
896 .iter()
897 .map(|tombstone| (tombstone.0.as_str(), tombstone.1)),
898 ),
899 );
900 for (collection, logical_id, old_id, new_id, xid, previous_xmax, old_xmax, epoch) in
901 versioned_updates
902 {
903 serializable_write_set.insert((collection.clone(), logical_id));
904 if self.xid_conflicts_with_snapshot(previous_xmax, snapshot, own_xids) {
905 return Err(Self::conflict_error(&collection, logical_id, previous_xmax));
906 }
907 if old_xmax != xid && self.xid_conflicts_with_snapshot(old_xmax, snapshot, own_xids) {
908 return Err(Self::conflict_error(&collection, logical_id, old_xmax));
909 }
910 self.check_logical_row_conflict(
911 &collection,
912 logical_id,
913 &[old_id, new_id],
914 &versions,
915 snapshot,
916 own_xids,
917 epoch,
918 )?;
919 }
920
921 for (collection, logical_id, id, xid, previous_xmax, xmax, epoch) in tombstones {
922 serializable_write_set.insert((collection.clone(), logical_id));
923 if self.xid_conflicts_with_snapshot(previous_xmax, snapshot, own_xids) {
924 return Err(Self::conflict_error(&collection, logical_id, previous_xmax));
925 }
926 if xmax != xid && self.xid_conflicts_with_snapshot(xmax, snapshot, own_xids) {
927 return Err(Self::conflict_error(&collection, logical_id, xmax));
928 }
929 self.check_logical_row_conflict(
930 &collection,
931 logical_id,
932 &[id],
933 &versions,
934 snapshot,
935 own_xids,
936 epoch,
937 )?;
938 }
939
940 if isolation == crate::storage::transaction::IsolationLevel::Serializable
941 && self
942 .inner
943 .transaction_state
944 .snapshot_manager()
945 .serializable_commit_would_be_dangerous(
946 *own_xids.iter().min().unwrap_or(&0),
947 &serializable_write_set,
948 )
949 {
950 return Err(RedDBError::Query(
951 "serialization conflict: serializable transaction would complete rw-antidependency dangerous structure".to_string(),
952 ));
953 }
954
955 Ok(())
956 }
957
958 pub(crate) fn check_queue_dedup_write_conflicts(
959 &self,
960 conn_id: u64,
961 snapshot: &crate::storage::transaction::snapshot::Snapshot,
962 own_xids: &std::collections::HashSet<crate::storage::transaction::snapshot::Xid>,
963 ) -> RedDBResult<()> {
964 let pending = self
965 .inner
966 .pending_queue_dedup
967 .read()
968 .get(&conn_id)
969 .cloned()
970 .unwrap_or_default();
971 if pending.is_empty() {
972 return Ok(());
973 }
974
975 let store = self.inner.db.store();
976 let Some(manager) = store.get_collection(crate::runtime::impl_queue::QUEUE_META_COLLECTION)
977 else {
978 return Ok(());
979 };
980
981 for (queue, dedup_key, metadata_id) in pending {
982 for candidate in manager.query_all(|entity| {
983 entity.data.as_row().is_some_and(|row| {
984 crate::runtime::impl_queue::row_text(row, "kind").as_deref()
985 == Some(crate::runtime::impl_queue::KIND_QUEUE_PUSH_DEDUP)
986 && crate::runtime::impl_queue::row_text(row, "queue").as_deref()
987 == Some(&queue)
988 && crate::runtime::impl_queue::row_text(row, "dedup_key").as_deref()
989 == Some(&dedup_key)
990 })
991 }) {
992 if candidate.id == metadata_id
993 || self
994 .inner
995 .transaction_state
996 .snapshot_manager()
997 .is_aborted(candidate.xmin)
998 {
999 continue;
1000 }
1001 if self.xid_conflicts_with_snapshot(candidate.xmin, snapshot, own_xids) {
1002 return Err(RedDBError::Query(format!(
1003 "serialization conflict: queue dedup key {queue}/{dedup_key} was modified by concurrent transaction {}",
1004 candidate.xmin
1005 )));
1006 }
1007 }
1008 }
1009 Ok(())
1010 }
1011
1012 pub(crate) fn restore_pending_write_stamps(&self, conn_id: u64) {
1013 let versioned_updates = self
1014 .inner
1015 .pending_versioned_updates
1016 .read()
1017 .get(&conn_id)
1018 .cloned()
1019 .unwrap_or_default();
1020 let tombstones = self
1021 .inner
1022 .pending_tombstones
1023 .read()
1024 .get(&conn_id)
1025 .cloned()
1026 .unwrap_or_default();
1027
1028 let store = self.inner.db.store();
1029 let _publication = store.vault_publication_lock.lock();
1030 for (collection, old_id, new_id, xid, _previous_xmax) in versioned_updates {
1031 if let Some(manager) = store.get_collection(&collection) {
1032 let epoch = manager
1033 .get(new_id)
1034 .and_then(|entity| entity.branch_version().map(|version| version.origin));
1035 if let Some(mut entity) = manager.get(old_id) {
1036 if let Some(epoch) = epoch {
1037 entity.set_branch_xmax(epoch, xid);
1038 } else {
1039 entity.set_xmax(xid);
1040 }
1041 let _ = manager.update(entity);
1042 }
1043 }
1044 }
1045 for (collection, id, xid, _previous_xmax, epoch) in tombstones {
1046 if let Some(manager) = store.get_collection(&collection) {
1047 if let Some(mut entity) = manager.get(id) {
1048 if let Some(epoch) = epoch {
1049 entity.set_branch_xmax(epoch, xid);
1050 } else {
1051 entity.set_xmax(xid);
1052 }
1053 let _ = manager.update(entity);
1054 }
1055 }
1056 }
1057 }
1058
1059 pub(crate) fn finalize_pending_versioned_updates(&self, conn_id: u64) {
1060 self.inner
1061 .pending_versioned_updates
1062 .write()
1063 .remove(&conn_id);
1064 }
1065
1066 pub(crate) fn finalize_pending_queue_dedup(&self, conn_id: u64) {
1067 self.inner.pending_queue_dedup.write().remove(&conn_id);
1068 }
1069
1070 pub(crate) fn discard_pending_queue_dedup(&self, conn_id: u64) {
1071 let Some(pending) = self.inner.pending_queue_dedup.write().remove(&conn_id) else {
1072 return;
1073 };
1074 let store = self.inner.db.store();
1075 for (_queue, _dedup_key, metadata_id) in pending {
1076 let _ = store.delete(
1077 crate::runtime::impl_queue::QUEUE_META_COLLECTION,
1078 metadata_id,
1079 );
1080 }
1081 }
1082
1083 pub(crate) fn revive_pending_versioned_updates(&self, conn_id: u64) -> RedDBResult<()> {
1084 let Some(pending) = self
1085 .inner
1086 .pending_versioned_updates
1087 .write()
1088 .remove(&conn_id)
1089 else {
1090 return Ok(());
1091 };
1092 for (collection, old_id, new_id, xid, previous_xmax) in pending.into_iter().rev() {
1094 let topology_lock = self.index_store_ref().collection_topology_lock(&collection);
1095 #[cfg(test)]
1096 self.index_store_ref().mutation_test_hook(
1097 &collection,
1098 super::index_store::MutationTestPhase::BeforeUndoTopology,
1099 );
1100 self.revive_versioned_update(
1101 &collection,
1102 old_id,
1103 new_id,
1104 xid,
1105 previous_xmax,
1106 topology_lock.read(),
1107 )?;
1108 }
1109 Ok(())
1110 }
1111
1112 pub(crate) fn revive_versioned_update(
1113 &self,
1114 collection: &str,
1115 old_id: crate::storage::EntityId,
1116 new_id: crate::storage::EntityId,
1117 xid: u64,
1118 previous_xmax: u64,
1119 _topology_guard: parking_lot::RwLockReadGuard<'_, ()>,
1120 ) -> RedDBResult<()> {
1121 let _indexed_mutation = self.index_store_ref().begin_indexed_mutation(collection);
1122 let store = self.inner.db.store();
1123 let _publication = store.vault_publication_lock.lock();
1124 let epoch = store
1125 .get(collection, new_id)
1126 .and_then(|entity| entity.branch_version().map(|version| version.origin));
1127 if let Some(new) = store.get(collection, new_id) {
1128 let fields = crate::application::ports::entity_row_fields_snapshot(&new);
1129 self.index_store_ref()
1130 .index_entity_delete(collection, new_id, &fields)
1131 .map_err(RedDBError::Internal)?;
1132 #[cfg(test)]
1133 self.index_store_ref().mutation_test_hook(
1134 collection,
1135 super::index_store::MutationTestPhase::UndoIndexRemoved,
1136 );
1137 }
1138 store
1139 .delete_batch(collection, &[new_id])
1140 .map_err(|error| RedDBError::Internal(error.to_string()))?;
1141 if let Some(manager) = store.get_collection(collection) {
1142 if let Some(mut old) = manager.get(old_id) {
1143 if epoch.map_or(old.xmax, |epoch| old.branch_xmax(epoch)) == xid {
1144 if let Some(epoch) = epoch {
1145 old.set_branch_xmax(epoch, previous_xmax);
1146 } else {
1147 old.set_xmax(previous_xmax);
1148 }
1149 manager
1150 .update(old.clone())
1151 .map_err(|error| RedDBError::Internal(error.to_string()))?;
1152 store.context_index().index_entity(collection, &old);
1153 let fields = crate::application::ports::entity_row_fields_snapshot(&old);
1154 self.index_store_ref()
1155 .index_entity_insert(collection, old_id, &fields)
1156 .map_err(RedDBError::Internal)?;
1157 }
1158 }
1159 }
1160 Ok(())
1161 }
1162
1163 pub(crate) fn finalize_pending_tombstones(&self, conn_id: u64) {
1168 let Some(pending) = self.inner.pending_tombstones.write().remove(&conn_id) else {
1169 return;
1170 };
1171 if pending.is_empty() {
1172 return;
1173 }
1174
1175 let store = self.inner.db.store();
1176 for (collection, id, _xid, _previous_xmax, _epoch) in pending {
1177 if let Some(manager) = store.get_collection(&collection) {
1178 manager.remove_metadata_expiry(id);
1179 }
1180 store.context_index().remove_entity(id);
1181 self.invalidate_result_cache_for_table(&collection);
1182 if self.inner.db.replication.is_none() {
1185 self.inner.cdc.emit(
1186 crate::replication::cdc::ChangeOperation::Delete,
1187 &collection,
1188 id.raw(),
1189 "entity",
1190 );
1191 }
1192 }
1193 }
1194
1195 pub(crate) fn revive_pending_tombstones(&self, conn_id: u64) {
1202 let Some(pending) = self.inner.pending_tombstones.write().remove(&conn_id) else {
1203 return;
1204 };
1205
1206 let store = self.inner.db.store();
1207 let _publication = store.vault_publication_lock.lock();
1208 for (collection, id, xid, previous_xmax, epoch) in pending {
1209 let Some(manager) = store.get_collection(&collection) else {
1210 continue;
1211 };
1212 if let Some(mut entity) = manager.get(id) {
1213 if epoch.map_or(entity.xmax, |epoch| entity.branch_xmax(epoch)) == xid {
1214 if let Some(epoch) = epoch {
1215 entity.set_branch_xmax(epoch, previous_xmax);
1216 } else {
1217 entity.set_xmax(previous_xmax);
1218 }
1219 let _ = manager.update(entity);
1220 }
1221 }
1222 }
1223 }
1224
1225 pub fn queue_wait_registry(
1227 &self,
1228 ) -> std::sync::Arc<crate::runtime::queue_wait_registry::QueueWaitRegistry> {
1229 self.inner.queue_wait_registry.clone()
1230 }
1231
1232 pub(crate) fn record_queue_wake(&self, scope: &str, queue: &str) {
1237 if self.current_xid().is_some() {
1238 let conn_id = current_connection_id();
1239 self.inner
1240 .pending_queue_wakes
1241 .write()
1242 .entry(conn_id)
1243 .or_default()
1244 .push((scope.to_string(), queue.to_string()));
1245 return;
1246 }
1247 self.inner.queue_wait_registry.notify(scope, queue);
1248 }
1249
1250 pub(crate) fn finalize_pending_queue_wakes(&self, conn_id: u64) {
1251 let Some(pending) = self.inner.pending_queue_wakes.write().remove(&conn_id) else {
1252 return;
1253 };
1254 for (scope, queue) in pending {
1255 self.inner.queue_wait_registry.notify(&scope, &queue);
1256 }
1257 }
1258
1259 pub(crate) fn discard_pending_queue_wakes(&self, conn_id: u64) {
1260 self.inner.pending_queue_wakes.write().remove(&conn_id);
1261 }
1262
1263 pub(crate) fn release_pending_claim_locks(&self, conn_id: u64) {
1264 self.inner
1265 .pending_claim_locks
1266 .write()
1267 .retain(|_, owner| *owner != conn_id);
1268 }
1269
1270 pub(crate) fn finalize_pending_kv_watch_events(&self, conn_id: u64) {
1271 let Some(pending) = self.inner.pending_kv_watch_events.write().remove(&conn_id) else {
1272 return;
1273 };
1274 for (_, event) in pending {
1275 self.cdc_emit_kv(
1276 event.op,
1277 &event.collection,
1278 &event.key,
1279 0,
1280 event.before,
1281 event.after,
1282 );
1283 }
1284 }
1285
1286 pub(crate) fn discard_pending_kv_watch_events(&self, conn_id: u64) {
1287 self.inner.pending_kv_watch_events.write().remove(&conn_id);
1288 }
1289
1290 pub(crate) fn stamp_xmin_if_in_txn(
1305 &self,
1306 collection: &str,
1307 id: crate::storage::unified::entity::EntityId,
1308 ) {
1309 let Some(xid) = self.current_xid() else {
1310 return;
1311 };
1312 let store = self.inner.db.store();
1313 let Some(manager) = store.get_collection(collection) else {
1314 return;
1315 };
1316 if let Some(mut entity) = manager.get(id) {
1317 entity.set_xmin(xid);
1318 let _ = manager.update(entity);
1319 }
1320 }
1321
1322 pub(crate) fn revive_tombstones_since(&self, conn_id: u64, stamper_xid: u64) -> usize {
1330 let store = self.inner.db.store();
1331 let _publication = store.vault_publication_lock.lock();
1332 let mut guard = self.inner.pending_tombstones.write();
1333 let Some(pending) = guard.get_mut(&conn_id) else {
1334 return 0;
1335 };
1336
1337 let mut revived = 0usize;
1338 pending.retain(|(collection, id, xid, previous_xmax, epoch)| {
1339 if *xid < stamper_xid {
1340 return true;
1342 }
1343 if let Some(manager) = store.get_collection(collection) {
1344 if let Some(mut entity) = manager.get(*id) {
1345 if epoch.map_or(entity.xmax, |epoch| entity.branch_xmax(epoch)) == *xid {
1346 if let Some(epoch) = epoch {
1347 entity.set_branch_xmax(*epoch, *previous_xmax);
1348 } else {
1349 entity.set_xmax(*previous_xmax);
1350 }
1351 let _ = manager.update(entity);
1352 revived += 1;
1353 }
1354 }
1355 }
1356 false
1357 });
1358 if pending.is_empty() {
1359 guard.remove(&conn_id);
1360 }
1361 revived
1362 }
1363
1364 pub fn current_snapshot(&self) -> crate::storage::transaction::snapshot::Snapshot {
1376 self.inner
1377 .transaction_state
1378 .current_snapshot(current_connection_id())
1379 }
1380
1381 pub fn current_xid(&self) -> Option<crate::storage::transaction::snapshot::Xid> {
1391 self.inner
1392 .transaction_state
1393 .writer_xid(current_connection_id())
1394 }
1395
1396 pub(crate) fn own_transaction_xids(&self) -> std::collections::HashSet<u64> {
1397 let mut xids = self
1398 .inner
1399 .transaction_state
1400 .own_xids(current_connection_id());
1401 if let Some(xid) = self.graph_insert_xid() {
1402 xids.insert(xid);
1403 }
1404 xids
1405 }
1406
1407 pub fn connection_in_transaction(&self, conn_id: u64) -> bool {
1414 self.inner.transaction_state.in_transaction(conn_id)
1415 }
1416
1417 pub fn snapshot_manager(&self) -> Arc<crate::storage::transaction::snapshot::SnapshotManager> {
1420 self.inner.transaction_state.snapshot_manager()
1421 }
1422
1423 pub(crate) fn mvcc_vacuum_cutoff_xid(&self) -> crate::storage::transaction::snapshot::Xid {
1424 self.mvcc_cutoff_xid(true)
1425 }
1426
1427 pub(crate) fn mvcc_vacuum_cutoff_xid_for(
1438 &self,
1439 collection: &str,
1440 ) -> RedDBResult<crate::storage::transaction::snapshot::Xid> {
1441 let addressable_by_as_of = collection != super::control_events::CONTROL_EVENTS_COLLECTION
1446 && (collection.starts_with("red_")
1447 || collection.starts_with("red.")
1448 || self.vcs_is_versioned(collection)?);
1449 Ok(self.mvcc_cutoff_xid(addressable_by_as_of))
1450 }
1451
1452 fn mvcc_cutoff_xid(
1453 &self,
1454 honor_commit_pins: bool,
1455 ) -> crate::storage::transaction::snapshot::Xid {
1456 let manager = self.inner.transaction_state.snapshot_manager();
1457 let next_xid = manager.peek_next_xid();
1458 let mut cutoff = next_xid;
1459 let oldest_required = if honor_commit_pins {
1460 manager.oldest_required_xid()
1461 } else {
1462 manager.oldest_live_required_xid()
1463 };
1464 if let Some(oldest_required) = oldest_required {
1465 cutoff = cutoff.min(oldest_required);
1466 }
1467 let retention_xids = self.config_u64("runtime.mvcc.vacuum_retention_xids", 0);
1468 if retention_xids > 0 {
1469 cutoff = cutoff.min(next_xid.saturating_sub(retention_xids));
1470 }
1471 cutoff
1472 }
1473
1474 pub fn current_txn_own_xids(
1479 &self,
1480 ) -> std::collections::HashSet<crate::storage::transaction::snapshot::Xid> {
1481 self.inner
1482 .transaction_state
1483 .own_xids(current_connection_id())
1484 }
1485}
1486
1487pub(crate) struct ChunkCheckpoints(bool);
1489
1490impl Drop for ChunkCheckpoints {
1491 fn drop(&mut self) {
1492 CHUNKS_CHECKPOINT_BY_VOLUME.with(|slot| slot.set(self.0));
1493 }
1494}