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