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