1use std::collections::BTreeMap;
13use std::fmt::Debug;
14use std::sync::Arc;
15
16use differential_dataflow::Hashable;
17use differential_dataflow::difference::Monoid;
18use differential_dataflow::lattice::Lattice;
19use futures::StreamExt;
20use futures::stream::FuturesUnordered;
21use mz_ore::cast::CastFrom;
22use mz_ore::instrument;
23use mz_persist_client::ShardId;
24use mz_persist_client::batch::{Batch, ProtoBatch};
25use mz_persist_types::txn::{TxnsCodec, TxnsEntry};
26use mz_persist_types::{Codec, Codec64, StepForward};
27use prost::Message;
28use timely::order::TotalOrder;
29use timely::progress::{Antichain, Timestamp};
30use tracing::debug;
31
32use crate::proto::ProtoIdBatch;
33use crate::txns::{Tidy, TxnsHandle};
34
35#[derive(Debug)]
37pub(crate) struct TxnWrite<K, V, T, D> {
38 pub(crate) batches: Vec<Batch<K, V, T, D>>,
39 pub(crate) staged: Vec<ProtoBatch>,
40 pub(crate) writes: Vec<(K, V, D)>,
41}
42
43impl<K, V, T, D> TxnWrite<K, V, T, D> {
44 pub fn merge(&mut self, other: Self) {
46 self.batches.extend(other.batches);
47 self.staged.extend(other.staged);
48 self.writes.extend(other.writes);
49 }
50}
51
52impl<K, V, T, D> Default for TxnWrite<K, V, T, D> {
53 fn default() -> Self {
54 Self {
55 batches: Vec::default(),
56 staged: Vec::default(),
57 writes: Vec::default(),
58 }
59 }
60}
61
62#[derive(Debug)]
64pub struct Txn<K, V, T, D> {
65 pub(crate) writes: BTreeMap<ShardId, TxnWrite<K, V, T, D>>,
66 tidy: Tidy,
67}
68
69impl<K, V, T, D> Txn<K, V, T, D>
70where
71 K: Debug + Codec,
72 V: Debug + Codec,
73 T: Timestamp + Lattice + TotalOrder + StepForward + Codec64 + Sync,
74 D: Debug + Monoid + Ord + Codec64 + Send + Sync,
75{
76 pub(crate) fn new() -> Self {
77 Txn {
78 writes: BTreeMap::default(),
79 tidy: Tidy::default(),
80 }
81 }
82
83 #[allow(clippy::unused_async)]
90 pub async fn write(&mut self, data_id: &ShardId, key: K, val: V, diff: D) {
91 self.writes
92 .entry(*data_id)
93 .or_default()
94 .writes
95 .push((key, val, diff))
96 }
97
98 pub fn write_batch(&mut self, data_id: &ShardId, batch: ProtoBatch) {
102 self.writes.entry(*data_id).or_default().staged.push(batch)
103 }
104
105 #[instrument(level = "debug", fields(ts = ?commit_ts))]
119 pub async fn commit_at<C>(
120 &mut self,
121 handle: &mut TxnsHandle<K, V, T, D, C>,
122 commit_ts: T,
123 ) -> Result<TxnApply<T>, T>
124 where
125 C: TxnsCodec,
126 {
127 let op = &Arc::clone(&handle.metrics).commit;
128 op.run(async {
129 let mut txns_upper = handle
130 .txns_write
131 .shared_upper()
132 .into_option()
133 .expect("txns shard should not be closed");
134
135 loop {
136 txns_upper = handle.txns_cache.update_ge(&txns_upper).await.clone();
137
138 if commit_ts < txns_upper {
143 debug!(
144 "commit_at {:?} mismatch current={:?}",
145 commit_ts, txns_upper
146 );
147 return Err(txns_upper);
148 }
149 for (data_id, _) in self.writes.iter() {
151 assert!(
152 handle
153 .txns_cache
154 .registered_at_progress(data_id, &txns_upper),
155 "{} should be registered to commit at {:?}",
156 data_id,
157 txns_upper,
158 );
159 }
160 debug!(
161 "commit_at {:?}: [{:?}, {:?}) begin",
162 commit_ts,
163 txns_upper,
164 commit_ts.step_forward(),
165 );
166
167 let txn_batches_updates = FuturesUnordered::new();
168 while let Some((data_id, updates)) = self.writes.pop_first() {
169 let data_write = handle.datas.take_write_for_commit(&data_id).unwrap_or_else(
170 || {
171 panic!(
172 "data shard {} must be registered with this Txn handle to commit",
173 data_id
174 )
175 },
176 );
177 let commit_ts = commit_ts.clone();
178 txn_batches_updates.push(async move {
179 let mut batches =
180 Vec::with_capacity(updates.staged.len() + updates.batches.len() + 1);
181
182 if !updates.writes.is_empty() {
184 let mut batch =
185 data_write.rewritable_builder(Antichain::from_elem(T::minimum()));
186 for (k, v, d) in updates.writes.iter() {
187 batch.add(k, v, &commit_ts, d).await.expect("valid usage");
188 }
189 let batch = batch
190 .finish(Antichain::from_elem(commit_ts.step_forward()))
191 .await
192 .expect("valid usage");
193 let batch = batch.into_transmittable_batch();
194 batches.push(batch);
195 }
196
197 batches.extend(updates.staged.into_iter());
199 batches.extend(
200 updates
201 .batches
202 .into_iter()
203 .map(|b| b.into_transmittable_batch()),
204 );
205
206 let batches: Vec<_> = batches
208 .into_iter()
209 .map(|batch| {
210 let mut batch = data_write.batch_from_transmittable_batch(batch);
211 batch
212 .rewrite_ts(
213 &Antichain::from_elem(commit_ts.clone()),
214 Antichain::from_elem(commit_ts.step_forward()),
215 )
216 .expect("invalid usage");
217 batch.into_transmittable_batch()
218 })
219 .collect();
220
221 let batch_updates = batches
222 .into_iter()
223 .map(|batch| {
224 let batch_raw = ProtoIdBatch::new(batch.clone()).encode_to_vec();
236 debug!(
237 "wrote {:.9} batch {}",
238 data_id.to_string(),
239 batch_raw.hashed(),
240 );
241 let update = C::encode(TxnsEntry::Append(
242 data_id,
243 T::encode(&commit_ts),
244 batch_raw,
245 ));
246 (batch, update)
247 })
248 .collect::<Vec<_>>();
249 (data_write, batch_updates)
250 })
251 }
252 let txn_batches_updates = txn_batches_updates.collect::<Vec<_>>().await;
253 let mut txns_updates = txn_batches_updates
254 .iter()
255 .flat_map(|(_, batch_updates)| batch_updates.iter().map(|(_, updates)| updates))
256 .map(|(key, val)| ((key, val), &commit_ts, 1))
257 .collect::<Vec<_>>();
258 let apply_is_empty = txns_updates.is_empty();
259
260 let filtered_retractions = handle
266 .read_cache()
267 .filter_retractions(&txns_upper, self.tidy.retractions.iter())
268 .map(|(batch_raw, (ts, data_id))| {
269 C::encode(TxnsEntry::Append(*data_id, *ts, batch_raw.clone()))
270 })
271 .collect::<Vec<_>>();
272 txns_updates.extend(
273 filtered_retractions
274 .iter()
275 .map(|(key, val)| ((key, val), &commit_ts, -1)),
276 );
277
278 let res = crate::small_caa(
279 || "txns commit",
280 &mut handle.txns_write,
281 &txns_updates,
282 txns_upper.clone(),
283 commit_ts.step_forward(),
284 )
285 .await;
286 match res {
287 Ok(()) => {
288 debug!(
289 "commit_at {:?}: [{:?}, {:?}) success",
290 commit_ts,
291 txns_upper,
292 commit_ts.step_forward(),
293 );
294 for (data_write, batch_updates) in txn_batches_updates {
297 for (batch, _) in batch_updates {
298 let batch = data_write
299 .batch_from_transmittable_batch(batch)
300 .into_hollow_batch();
301 handle.metrics.batches.commit_count.inc();
302 handle
303 .metrics
304 .batches
305 .commit_bytes
306 .inc_by(u64::cast_from(batch.encoded_size_bytes()));
307 }
308 handle.datas.put_write_for_commit(data_write);
309 }
310 return Ok(TxnApply {
311 is_empty: apply_is_empty,
312 commit_ts,
313 });
314 }
315 Err(new_txns_upper) => {
316 handle.metrics.commit.retry_count.inc();
317 assert!(txns_upper < new_txns_upper);
318 txns_upper = new_txns_upper;
319 for (data_write, batch_updates) in txn_batches_updates {
320 let batches = batch_updates
321 .into_iter()
322 .map(|(batch, _)| {
323 data_write.batch_from_transmittable_batch(batch.clone())
324 })
325 .collect();
326 let txn_write = TxnWrite {
327 writes: Vec::new(),
328 staged: Vec::new(),
329 batches,
330 };
331 self.writes.insert(data_write.shard_id(), txn_write);
332 handle.datas.put_write_for_commit(data_write);
333 }
334 let _ = handle.txns_cache.update_ge(&txns_upper).await;
335 continue;
336 }
337 }
338 }
339 })
340 .await
341 }
342
343 pub fn merge(&mut self, other: Self) {
345 for (data_id, writes) in other.writes {
346 self.writes.entry(data_id).or_default().merge(writes);
347 }
348 self.tidy.merge(other.tidy);
349 }
350
351 pub fn tidy(&mut self, tidy: Tidy) {
355 self.tidy.merge(tidy);
356 }
357
358 pub fn take_tidy(&mut self) -> Tidy {
361 std::mem::take(&mut self.tidy)
362 }
363}
364
365#[derive(Debug)]
368#[cfg_attr(any(test, debug_assertions), derive(PartialEq))]
369pub struct TxnApply<T> {
370 is_empty: bool,
371 pub(crate) commit_ts: T,
372}
373
374impl<T> TxnApply<T> {
375 pub async fn apply<K, V, D, C>(self, handle: &mut TxnsHandle<K, V, T, D, C>) -> Tidy
377 where
378 K: Debug + Codec,
379 V: Debug + Codec,
380 T: Timestamp + Lattice + TotalOrder + StepForward + Codec64 + Sync,
381 D: Debug + Monoid + Ord + Codec64 + Send + Sync,
382 C: TxnsCodec,
383 {
384 debug!("txn apply {:?}", self.commit_ts);
385 handle.apply_le(&self.commit_ts).await
386 }
387
388 pub fn is_empty(&self) -> bool {
393 self.is_empty
394 }
395}
396
397#[cfg(test)]
398mod tests {
399 use std::time::{Duration, SystemTime};
400
401 use futures::StreamExt;
402 use futures::stream::FuturesUnordered;
403 use mz_ore::assert_err;
404 use mz_persist_client::PersistClient;
405
406 use crate::tests::writer;
407 use crate::txn_cache::TxnsCache;
408
409 use super::*;
410
411 #[mz_ore::test(tokio::test)]
412 #[cfg_attr(miri, ignore)] async fn commit_at() {
414 let client = PersistClient::new_for_tests().await;
415 let mut txns = TxnsHandle::expect_open(client.clone()).await;
416 let mut cache = TxnsCache::expect_open(0, &txns).await;
417 let d0 = txns.expect_register(1).await;
418 let d1 = txns.expect_register(2).await;
419
420 let mut txn = txns.begin();
422 txn.write(&d0, "0".into(), (), 1).await;
423 let mut other = txns.begin();
424 other.write(&d0, "1".into(), (), 1).await;
425 other.write(&d1, "A".into(), (), 1).await;
426 txn.merge(other);
427 txn.commit_at(&mut txns, 3).await.unwrap();
428
429 txns.begin().commit_at(&mut txns, 5).await.unwrap();
431
432 let mut txn = txns.begin();
435 txn.write(&d0, "2".into(), (), 1).await;
436 assert_eq!(txn.commit_at(&mut txns, 4).await, Err(6));
437 txn.commit_at(&mut txns, 6).await.unwrap();
438 txns.apply_le(&6).await;
439
440 let expected_d0 = vec!["0".to_owned(), "1".to_owned(), "2".to_owned()];
441 let actual_d0 = cache.expect_snapshot(&client, d0, 6).await;
442 assert_eq!(actual_d0, expected_d0);
443
444 let expected_d1 = vec!["A".to_owned()];
445 let actual_d1 = cache.expect_snapshot(&client, d1, 6).await;
446 assert_eq!(actual_d1, expected_d1);
447 }
448
449 #[mz_ore::test(tokio::test)]
450 #[cfg_attr(miri, ignore)] async fn apply_and_tidy() {
452 let mut txns = TxnsHandle::expect_open(PersistClient::new_for_tests().await).await;
453 let log = txns.new_log();
454 let mut cache = TxnsCache::expect_open(0, &txns).await;
455 let d0 = txns.expect_register(1).await;
456
457 let mut txn = txns.begin_test();
460 txn.write(&d0, "2".into(), (), 1).await;
461 let apply_2 = txn.commit_at(&mut txns, 2).await.unwrap();
462 log.record_txn(2, &txn);
463 assert_eq!(apply_2.is_empty(), false);
464 let _ = cache.update_gt(&2).await;
465 cache.mark_register_applied(&2);
466 assert_eq!(cache.min_unapplied_ts(), &2);
467 assert_eq!(cache.unapplied().count(), 1);
468
469 let tidy_2 = apply_2.apply(&mut txns).await;
472 assert_eq!(cache.min_unapplied_ts(), &2);
473
474 txns.tidy_at(3, tidy_2).await.unwrap();
476 let _ = cache.update_gt(&3).await;
477 assert_eq!(cache.min_unapplied_ts(), &4);
478 assert_eq!(cache.unapplied().count(), 0);
479
480 let tidy_4 = txns.expect_commit_at(4, d0, &["4"], &log).await;
483 let _ = cache.update_gt(&4).await;
484 assert_eq!(cache.min_unapplied_ts(), &4);
485 let mut txn0 = txns.begin_test();
486 txn0.write(&d0, "5".into(), (), 1).await;
487 txn0.tidy(tidy_4);
488 let mut txn1 = txns.begin_test();
489 txn1.merge(txn0);
490 let apply_5 = txn1.commit_at(&mut txns, 5).await.unwrap();
491 log.record_txn(5, &txn1);
492 let _ = cache.update_gt(&5).await;
493 assert_eq!(cache.min_unapplied_ts(), &5);
494 let tidy_5 = apply_5.apply(&mut txns).await;
495
496 let tidy_6 = txns.expect_commit_at(6, d0, &["6"], &log).await;
498 txns.tidy_at(7, tidy_6).await.unwrap();
499 let _ = cache.update_gt(&7).await;
500 assert_eq!(cache.min_unapplied_ts(), &8);
501
502 txns.tidy_at(8, tidy_5).await.unwrap();
505 let _ = cache.update_gt(&8).await;
506 assert_eq!(cache.min_unapplied_ts(), &9);
507
508 let tidy_9 = txns.expect_commit_at(9, d0, &["9"], &log).await;
510 let tidy_10 = txns.expect_commit_at(10, d0, &["10"], &log).await;
511 let mut txn = txns.begin();
512 txn.tidy(tidy_9);
513 let mut tidy_9 = txn.take_tidy();
514 tidy_9.merge(tidy_10);
515 txns.tidy_at(11, tidy_9).await.unwrap();
516 let _ = cache.update_gt(&11).await;
517 assert_eq!(cache.min_unapplied_ts(), &12);
518
519 let tidy_12 = txns.expect_commit_at(12, d0, &["12"], &log).await;
521 assert_eq!(txns.tidy_at(12, tidy_12).await, Err(13));
522
523 let () = log.assert_snapshot(d0, 12).await;
524 }
525
526 #[mz_ore::test(tokio::test(flavor = "multi_thread"))]
527 #[cfg_attr(miri, ignore)] async fn conflicting_writes() {
529 fn jitter() -> u64 {
530 let time = SystemTime::UNIX_EPOCH.elapsed().unwrap();
532 u64::from(time.subsec_micros() % 20)
533 }
534
535 let client = PersistClient::new_for_tests().await;
536 let mut txns = TxnsHandle::expect_open(client.clone()).await;
537 let log = txns.new_log();
538 let mut cache = TxnsCache::expect_open(0, &txns).await;
539 let d0 = txns.expect_register(1).await;
540
541 const NUM_WRITES: usize = 25;
542 let tasks = FuturesUnordered::new();
543 for idx in 0..NUM_WRITES {
544 let mut txn = txns.begin_test();
545 txn.write(&d0, format!("{:05}", idx), (), 1).await;
546 let (txns_id, client, log) = (txns.txns_id(), client.clone(), log.clone());
547
548 let task = async move {
549 let mut txns = TxnsHandle::expect_open_id(client.clone(), txns_id).await;
550 let mut register_ts = 1;
551 loop {
552 let data_write = writer(&client, d0).await;
553 match txns.register(register_ts, [data_write]).await {
554 Ok(_) => {
555 debug!("{} registered at {}", idx, register_ts);
556 break;
557 }
558 Err(ts) => {
559 register_ts = ts;
560 continue;
561 }
562 }
563 }
564
565 let jitter_ms = jitter();
568 let mut commit_ts = register_ts + 1 + jitter_ms;
569 let apply = loop {
570 let () = tokio::time::sleep(Duration::from_millis(jitter_ms)).await;
571 match txn.commit_at(&mut txns, commit_ts).await {
572 Ok(apply) => break apply,
573 Err(new_commit_ts) => commit_ts = new_commit_ts,
574 }
575 };
576 debug!("{} committed at {}", idx, commit_ts);
577 log.record_txn(commit_ts, &txn);
578
579 let () = tokio::time::sleep(Duration::from_millis(jitter_ms)).await;
581 let tidy = apply.apply(&mut txns).await;
582
583 let jitter_ms = jitter();
585 let mut txn = txns.begin();
586 txn.tidy(tidy);
587 let mut tidy_ts = commit_ts + jitter_ms;
588 loop {
589 let () = tokio::time::sleep(Duration::from_millis(jitter_ms)).await;
590 match txn.commit_at(&mut txns, tidy_ts).await {
591 Ok(apply) => {
592 debug!("{} tidied at {}", idx, tidy_ts);
593 assert!(apply.is_empty());
594 return commit_ts;
595 }
596 Err(new_tidy_ts) => tidy_ts = new_tidy_ts,
597 }
598 }
599 };
600 tasks.push(task)
601 }
602
603 let max_commit_ts = tasks
604 .collect::<Vec<_>>()
605 .await
606 .into_iter()
607 .max()
608 .unwrap_or_default();
609
610 let expected = (0..NUM_WRITES)
613 .map(|x| format!("{:05}", x))
614 .collect::<Vec<_>>();
615 let actual = cache.expect_snapshot(&client, d0, max_commit_ts).await;
616 assert_eq!(actual, expected);
617 log.assert_snapshot(d0, max_commit_ts).await;
618 }
619
620 #[mz_ore::test(tokio::test)]
621 #[cfg_attr(miri, ignore)] async fn tidy_race() {
623 let client = PersistClient::new_for_tests().await;
624 let mut txns0 = TxnsHandle::expect_open(client.clone()).await;
625 let log = txns0.new_log();
626 let d0 = txns0.expect_register(1).await;
627
628 let tidy0 = txns0.expect_commit_at(2, d0, &["foo"], &log).await;
630
631 let mut txns1 = TxnsHandle::expect_open_id(client.clone(), txns0.txns_id()).await;
633 let d1 = txns1.expect_register(3).await;
634 let tidy1 = txns1.expect_commit_at(4, d1, &["foo"], &log).await;
635 let () = txns1.tidy_at(5, tidy1).await.unwrap();
636
637 let () = txns0.tidy_at(6, tidy0).await.unwrap();
640
641 let mut cache = TxnsCache::expect_open(0, &txns0).await;
644 let _ = cache.update_gt(&6).await;
645 assert_eq!(cache.validate(), Ok(()));
646
647 log.assert_snapshot(d0, 6).await;
648 log.assert_snapshot(d1, 6).await;
649 }
650
651 #[mz_ore::test(tokio::test)]
654 #[cfg_attr(miri, ignore)] async fn commit_unregistered_table() {
656 let client = PersistClient::new_for_tests().await;
657 let mut txns = TxnsHandle::expect_open(client.clone()).await;
658
659 let commit = mz_ore::task::spawn(|| "", {
661 let (txns_id, client) = (txns.txns_id(), client.clone());
662 async move {
663 let mut txns = TxnsHandle::expect_open_id(client, txns_id).await;
664 let mut txn = txns.begin();
665 txn.write(&ShardId::new(), "foo".into(), (), 1).await;
666 txn.commit_at(&mut txns, 1).await
667 }
668 })
669 .into_tokio_handle();
670 assert_err!(commit.await);
671
672 let d0 = txns.expect_register(2).await;
673 txns.forget(3, [d0]).await.unwrap();
674
675 let commit = mz_ore::task::spawn(|| "", {
677 let (txns_id, client) = (txns.txns_id(), client.clone());
678 async move {
679 let mut txns = TxnsHandle::expect_open_id(client, txns_id).await;
680 let mut txn = txns.begin();
681 txn.write(&d0, "foo".into(), (), 1).await;
682 txn.commit_at(&mut txns, 4).await
683 }
684 })
685 .into_tokio_handle();
686 assert_err!(commit.await);
687 }
688
689 #[mz_ore::test(tokio::test)]
690 #[cfg_attr(miri, ignore)] async fn commit_retry() {
692 let client = PersistClient::new_for_tests().await;
693 let mut txns = TxnsHandle::expect_open(client.clone()).await;
694 let mut cache = TxnsCache::expect_open(0, &txns).await;
695 let d0 = txns.expect_register(1).await;
696 let d1 = txns.expect_register(2).await;
697
698 let mut txn = txns.begin();
700 txn.write(&d0, "0".into(), (), 1).await;
701 let mut other = txns.begin();
702 other.write(&d1, "42".into(), (), 1).await;
703 other.commit_at(&mut txns, 3).await.unwrap();
704 let upper = txn.commit_at(&mut txns, 3).await.unwrap_err();
705 assert_eq!(upper, 4);
706
707 txn.write(&d0, "1".into(), (), 1).await;
709 txn.commit_at(&mut txns, 4).await.unwrap();
710 txns.apply_le(&4).await;
711
712 let expected_d0 = vec!["0".to_owned(), "1".to_owned()];
713 let actual_d0 = cache.expect_snapshot(&client, d0, 4).await;
714 assert_eq!(actual_d0, expected_d0);
715 }
716}