1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

use std::cmp;
use std::collections::btree_map::Entry;
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};

use futures::future::join_all;
use futures::FutureExt;
use futures::{
    future::{self, try_join, try_join3, try_join_all, BoxFuture},
    TryFutureExt,
};
use mz_ore::metrics::MetricsFutureExt;
use mz_ore::{cast::CastFrom, collections::CollectionExt};
use mz_stash_types::{InternalStashError, StashError};
use timely::progress::Antichain;
use timely::PartialOrder;
use tokio::sync::{mpsc, oneshot};
use tokio_postgres::{types::ToSql, Client};

use crate::postgres::{ConsolidateRequest, CountedStatements};
use crate::{AntichainFormatter, AppendBatch, Data, Diff, Id, Stash, StashCollection, Timestamp};

/// The limit AFTER which to split an update batch (that is, we will ship an update that
/// exceeds this number, but then start another batch).
///
/// Cockroach's default limit for sql.conn.max_read_buffer_message_size is 16MiB
/// <https://github.com/cockroachdb/cockroach/blob/7e4e0b195cd61da6cd7a719a5b9aa2e84f68d475/pkg/sql/pgwire/pgwirebase/encoding.go#L50>.
/// Use a number well under that but still big ish that most things won't ever need to
/// batch. Because we are only estimating the value size and ignoring various other
/// things that contribute to the total pgwire message size, having a 14MiB headspace
/// seems safe here.
pub const INSERT_BATCH_SPLIT_SIZE: usize = 2 * 1024 * 1024;

/// [`tokio_postgres`] has a maximum number of arguments it supports when executing a query. This
/// is the limit at which to split a batch to make sure we don't try to include too many elements
/// in any one update.
pub(crate) const MAX_INSERT_ARGUMENTS: u16 = u16::MAX / 4;

impl Stash {
    /// Transactionally executes closure `f`.
    pub async fn with_transaction<F, T>(&mut self, f: F) -> Result<T, StashError>
    where
        F: FnOnce(Transaction) -> BoxFuture<Result<T, StashError>> + Clone + Sync + Send + 'static,
    {
        let (res, mut cons_rx, txn_collections) = self
            .transact(|stmts, client, collections| {
                let f = f.clone();
                let (cons_tx, cons_rx) = mpsc::unbounded_channel();
                let txn_collections = Arc::new(Mutex::new(BTreeMap::new()));
                let tx = Transaction {
                    stmts,
                    client,
                    consolidations: cons_tx,
                    savepoint: Arc::new(Mutex::new(false)),
                    sinces: Arc::new(Mutex::new(BTreeMap::new())),
                    uppers: Arc::new(Mutex::new(BTreeMap::new())),
                    stash_collections: collections,
                    txn_collections: Arc::clone(&txn_collections),
                };
                Box::pin(async move {
                    let res = f(tx).await?;
                    Ok((res, cons_rx, txn_collections))
                })
            })
            .await?;
        while let Some(cons) = cons_rx.recv().await {
            self.sinces_tx
                .send(cons)
                .expect("consolidator unexpectedly gone");
        }
        self.collections
            .extend(std::mem::take(&mut *txn_collections.lock().unwrap()));
        Ok(res)
    }
}

pub struct Transaction<'a> {
    stmts: &'a CountedStatements<'a>,
    client: &'a Client,
    // The set of consolidations that need to be performed if the transaction
    // succeeds.
    consolidations: mpsc::UnboundedSender<ConsolidateRequest>,
    // Savepoint state to enforce the invariant that only one SAVEPOINT is
    // active at once.
    savepoint: Arc<Mutex<bool>>,

    // Cached sinces and uppers for this transaction. These are set on first
    // query and updated on seal/compact.
    sinces: Arc<Mutex<BTreeMap<Id, Antichain<Timestamp>>>>,
    uppers: Arc<Mutex<BTreeMap<Id, Antichain<Timestamp>>>>,

    // Collections cached by the outer Stash.
    stash_collections: &'a BTreeMap<String, Id>,
    // Collections discovered by this transaction.
    txn_collections: Arc<Mutex<BTreeMap<String, Id>>>,
}

impl<'a> Transaction<'a> {
    /// Executes f in a SAVEPOINT. RELEASE if f returns Ok, ROLLBACK if f
    /// returns Err. This must be used for any fn that performs any falliable
    /// operation after its first write. This includes multiple write operations
    /// in a row (any function with multpile writes must use this function).
    async fn in_savepoint<'res, F, T>(&self, f: F) -> Result<T, StashError>
    where
        F: FnOnce() -> BoxFuture<'res, Result<T, StashError>>,
    {
        // Savepoints cannot be used recursively, so panic if that happened.
        {
            // Put this in a block to convince the rust compiler that savepoint
            // won't be used across the await.
            let mut savepoint = self.savepoint.lock().unwrap();
            if *savepoint {
                panic!("cannot call savepoint recursively");
            }
            *savepoint = true;
        };

        self.client.batch_execute("SAVEPOINT txn_savepoint").await?;
        let res = match f().await {
            Ok(t) => {
                self.client
                    .batch_execute("RELEASE SAVEPOINT txn_savepoint")
                    .await?;
                Ok(t)
            }
            Err(err) => {
                self.client
                    .batch_execute("ROLLBACK TO SAVEPOINT txn_savepoint")
                    .await?;
                Err(err)
            }
        };

        let mut savepoint = self.savepoint.lock().unwrap();
        assert!(*savepoint);
        *savepoint = false;

        res
    }

    #[mz_ore::instrument(level = "debug")]
    pub async fn collection<K, V>(&self, name: &str) -> Result<StashCollection<K, V>, StashError>
    where
        K: Data,
        V: Data,
    {
        if let Some(id) = self.stash_collections.get(name) {
            return Ok(StashCollection::new(*id));
        }

        let (statement, histogram) = self.stmts.collection();
        let collection_id_opt: Option<_> = self
            .client
            .query_one(statement, &[&name])
            .wall_time()
            .observe(histogram)
            .await
            .map(|row| row.get("collection_id"))
            .ok();

        let collection_id = match collection_id_opt {
            Some(id) => id,
            None => {
                let collection_id = self
                    .client
                    .query_one(
                        "INSERT INTO collections (name) VALUES ($1) RETURNING collection_id",
                        &[&name],
                    )
                    .await?
                    .get("collection_id");
                self.client
                    .execute(
                        "INSERT INTO sinces (collection_id, since) VALUES ($1, $2)",
                        &[&collection_id, &Timestamp::MIN],
                    )
                    .await?;
                self.client
                    .execute(
                        "INSERT INTO uppers (collection_id, upper) VALUES ($1, $2)",
                        &[&collection_id, &Timestamp::MIN],
                    )
                    .await?;
                collection_id
            }
        };

        self.txn_collections
            .lock()
            .unwrap()
            .insert(name.to_string(), collection_id);
        Ok(StashCollection::new(collection_id))
    }

    /// Returns the ids and names of all collections.
    #[mz_ore::instrument(level = "debug")]
    pub async fn collections(&self) -> Result<BTreeMap<Id, String>, StashError> {
        let rows = self
            .client
            .query("SELECT name, collection_id FROM collections", &[])
            .await?;
        let names = rows
            .into_iter()
            .map(|row| (row.get("collection_id"), row.get("name")));
        Ok(BTreeMap::from_iter(names))
    }

    // TODO(jkosh44) Only used in tests.
    #[mz_ore::instrument(level = "debug")]
    pub(crate) async fn consolidate(&self, id: Id) -> Result<(), StashError> {
        let since = self.since(id).await?;
        self.consolidations
            .send(ConsolidateRequest {
                id,
                since,
                done: None,
            })
            .unwrap();
        Ok(())
    }

    #[mz_ore::instrument(level = "debug")]
    pub(crate) async fn upper(
        &self,
        collection_id: Id,
    ) -> Result<Antichain<Timestamp>, StashError> {
        // We can't use .entry here because that would require holding the
        // MutexGuard across the .await.
        if let Some(entry) = self.uppers.lock().unwrap().get(&collection_id) {
            return Ok(entry.clone());
        }
        let (statement, histogram) = self.stmts.upper();
        let upper: Option<Timestamp> = self
            .client
            .query_one(statement, &[&collection_id])
            .wall_time()
            .observe(histogram)
            .await?
            .get("upper");
        let upper = Antichain::from_iter(upper);
        maybe_update_antichain(&self.uppers, collection_id, upper.clone());
        Ok(upper)
    }

    pub(crate) async fn since(
        &self,
        collection_id: Id,
    ) -> Result<Antichain<Timestamp>, StashError> {
        // We can't use .entry here because that would require holding the
        // MutexGuard across the .await.
        if let Some(entry) = self.sinces.lock().unwrap().get(&collection_id) {
            return Ok(entry.clone());
        }
        let (statement, histogram) = self.stmts.since();
        let since: Option<Timestamp> = self
            .client
            .query_one(statement, &[&collection_id])
            .wall_time()
            .observe(histogram)
            .await?
            .get("since");
        let since = Antichain::from_iter(since);
        maybe_update_antichain(&self.sinces, collection_id, since.clone());
        Ok(since)
    }

    /// Iterates over a collection.
    #[mz_ore::instrument(level = "debug")]
    pub async fn iter<K, V>(
        &self,
        collection: StashCollection<K, V>,
    ) -> Result<Vec<((K, V), Timestamp, Diff)>, StashError>
    where
        K: Data,
        V: Data,
    {
        let mut rows = self.iter_raw(collection.id).await?.collect();
        differential_dataflow::consolidation::consolidate_updates(&mut rows);

        // Deserialize the rows into the actual keys and values.
        let rows = rows
            .into_iter()
            .map(|((key, val), ts, diff)| {
                let key = K::decode(key.as_slice()).expect("serialization to roundtrip");
                let val = V::decode(val.as_slice()).expect("serialization to roundtrip");

                ((key, val), ts, diff)
            })
            .collect();

        Ok(rows)
    }

    /// Iterates over a collection, returning the raw data on disk, unconsolidated.
    #[mz_ore::instrument(level = "debug")]
    pub(crate) async fn iter_raw(
        &self,
        id: Id,
    ) -> Result<impl Iterator<Item = ((Vec<u8>, Vec<u8>), Timestamp, Diff)>, StashError> {
        let since = match self.since(id).await?.into_option() {
            Some(since) => since,
            None => {
                return Err(StashError::from(
                    "cannot iterate collection with empty since frontier",
                ));
            }
        };
        let (statement, histogram) = self.stmts.iter();
        let rows = self
            .client
            .query(statement, &[&id])
            .wall_time()
            .observe(histogram)
            .await?
            .into_iter()
            .map(move |row| {
                let key = row.get("key");
                let value = row.get("value");
                let time = row.get("time");
                let diff: Diff = row.get("diff");
                ((key, value), cmp::max(time, since), diff)
            });
        Ok(rows)
    }

    /// Iterates over the values of a key.
    #[mz_ore::instrument(level = "debug")]
    pub(crate) async fn iter_key<K, V>(
        &self,
        collection: StashCollection<K, V>,
        key: &K,
    ) -> Result<Vec<(V, Timestamp, Diff)>, StashError>
    where
        K: Data,
        V: Data,
    {
        let key = key.encode_to_vec();
        let (statement, histogram) = self.stmts.iter_key();
        let (since, rows) = future::try_join(
            self.since(collection.id),
            self.client
                .query(statement, &[&collection.id, &key])
                .map_err(|err| err.into())
                .wall_time()
                .observe(histogram),
        )
        .await?;
        let since = match since.into_option() {
            Some(since) => since,
            None => {
                return Err(StashError::from(
                    "cannot iterate collection with empty since frontier",
                ));
            }
        };
        let mut rows = rows
            .into_iter()
            .map(|row| {
                let value: Vec<u8> = row.try_get("value")?;
                let value = V::decode(value.as_slice())?;
                let time = row.try_get("time")?;
                let diff = row.try_get("diff")?;
                Ok::<_, StashError>((value, cmp::max(time, since), diff))
            })
            .collect::<Result<Vec<_>, _>>()?;
        differential_dataflow::consolidation::consolidate_updates(&mut rows);
        Ok(rows)
    }

    /// Returns the most recent timestamp at which sealed entries can be read.
    #[mz_ore::instrument(level = "debug")]
    async fn peek_timestamp_id(&self, id: Id) -> Result<Timestamp, StashError> {
        let (since, upper) = try_join(self.since(id), self.upper(id)).await?;
        if PartialOrder::less_equal(&upper, &since) {
            return Err(StashError {
                inner: InternalStashError::PeekSinceUpper(format!(
                    "collection {} since {} is not less than upper {}",
                    id,
                    AntichainFormatter(&since),
                    AntichainFormatter(&upper)
                )),
            });
        }
        match upper.as_option() {
            Some(ts) => match ts.checked_sub(1) {
                Some(ts) => Ok(ts),
                None => Err("could not determine peek timestamp".into()),
            },
            None => Ok(Timestamp::MAX),
        }
    }

    /// Returns the most recent timestamp at which sealed entries can be read.
    #[mz_ore::instrument(level = "debug")]
    pub(crate) async fn peek_timestamp<K, V>(
        &self,
        collection: StashCollection<K, V>,
    ) -> Result<Timestamp, StashError>
    where
        K: Data,
        V: Data,
    {
        self.peek_timestamp_id(collection.id).await
    }

    /// Returns the current value of sealed entries.
    ///
    /// Entries are iterated in `(key, value)` order and are guaranteed to be
    /// consolidated.
    ///
    /// Sealed entries are those with timestamps less than the collection's upper
    /// frontier.
    #[mz_ore::instrument(level = "debug")]
    pub(crate) async fn peek<K, V>(
        &self,
        collection: StashCollection<K, V>,
    ) -> Result<Vec<(K, V, Diff)>, StashError>
    where
        K: Data,
        V: Data,
    {
        let timestamp = self.peek_timestamp(collection).await?;
        let mut rows: Vec<_> = self
            .iter(collection)
            .await?
            .into_iter()
            .filter_map(|((k, v), data_ts, diff)| {
                if data_ts.less_equal(&timestamp) {
                    Some((k, v, diff))
                } else {
                    None
                }
            })
            .collect();
        differential_dataflow::consolidation::consolidate_updates(&mut rows);
        Ok(rows)
    }

    /// Returns the current k,v pairs of sealed entries, erroring if there is more
    /// than one entry for a given key or the multiplicity is not 1 for each key.
    ///
    /// Sealed entries are those with timestamps less than the collection's upper
    /// frontier.
    #[mz_ore::instrument(level = "debug")]
    pub async fn peek_one<K, V>(
        &self,
        collection: StashCollection<K, V>,
    ) -> Result<BTreeMap<K, V>, StashError>
    where
        K: Data,
        V: Data,
    {
        let rows = self.peek(collection).await?;
        let mut res = BTreeMap::new();
        for (k, v, diff) in rows {
            if diff != 1 {
                return Err(format!("unexpected peek multiplicity of {diff}").into());
            }
            if res.insert(k, v).is_some() {
                return Err(format!("duplicate peek keys for collection {}", collection.id).into());
            }
        }
        Ok(res)
    }

    /// Returns the current sealed value for the given key, erroring if there is
    /// more than one entry for the key or its multiplicity is not 1.
    ///
    /// Sealed entries are those with timestamps less than the collection's upper
    /// frontier.
    #[mz_ore::instrument(level = "debug")]
    pub async fn peek_key_one<K, V>(
        &self,
        collection: StashCollection<K, V>,
        key: &K,
    ) -> Result<Option<V>, StashError>
    where
        K: Data,
        V: Data,
    {
        let timestamp = self.peek_timestamp(collection).await?;
        let mut rows: Vec<_> = self
            .iter_key(collection, key)
            .await?
            .into_iter()
            .filter_map(|(v, data_ts, diff)| {
                if data_ts.less_equal(&timestamp) {
                    Some((v, diff))
                } else {
                    None
                }
            })
            .collect();
        differential_dataflow::consolidation::consolidate(&mut rows);
        let v = match rows.len() {
            1 => {
                let (v, diff) = rows.into_element();
                match diff {
                    1 => Some(v),
                    0 => None,
                    _ => return Err("multiple values unexpected".into()),
                }
            }
            0 => None,
            _ => return Err("multiple values unexpected".into()),
        };
        Ok(v)
    }

    /// Applies batches to the current transaction. If any batch fails and in
    /// error returned, all other applications are rolled back.
    #[mz_ore::instrument(level = "debug")]
    pub async fn append(
        &self,
        batches: Vec<AppendBatch>,
    ) -> Result<BoxFuture<'static, ()>, StashError> {
        if batches.is_empty() {
            return Ok(Box::pin(futures::future::ready(())));
        }

        let consolidations = self
            .in_savepoint(|| {
                Box::pin(async move {
                    let futures = batches.into_iter().map(
                        |AppendBatch {
                             collection_id,
                             lower,
                             upper,
                             entries,
                             ..
                         }| async move {
                            // Clone to appease rust async.
                            let compact = lower.clone();
                            let lower1 = lower.clone();
                            let lower2 = lower.clone();
                            let upper1 = upper.clone();
                            // The new upper must be validated before being sealed.
                            // Compaction can be done in any order because none of
                            // update/seal care about what the since is. Update, although it
                            // cares about the upper, can also be done in any order because
                            // we pass in the old upper, so it's not a problem if the seal
                            // has executed already since update won't query the current
                            // upper.
                            try_join3(
                                    async move {
                                        let current_upper = self.upper(collection_id).await?;
                                        if current_upper != lower1 {
                                            return Err(StashError::from(format!(
                                                "unexpected lower, got {:?}, expected {:?}",
                                                current_upper, lower1
                                            )));
                                        }

                                        self.seal(collection_id, upper1, Some(lower)).await
                                    },
                                    async move {
                                        self.update(collection_id, &entries, Some(lower2)).await
                                    },
                                    async move {
                                        self.compact(collection_id, &compact, Some(upper)).await
                                    },
                                )
                                .await?;

                            let (tx, rx) = oneshot::channel();
                            let request = ConsolidateRequest {
                                id: collection_id,
                                since: self.since(collection_id).await?,
                                done: Some(tx),
                            };

                            Ok::<_, StashError>((request, rx))
                        },
                    );
                    try_join_all(futures).await
                })
            })
            .await?;

        let mut notifs = Vec::with_capacity(consolidations.len());
        for (req, notif) in consolidations {
            self.consolidations.send(req).unwrap();
            notifs.push(notif);
        }

        // Note: we ignore the result of the Consolidation requests because consolidation cannot fail.
        Ok(Box::pin(join_all(notifs).map(|_| ())))
    }

    /// Like update, but starts a savepoint.
    #[mz_ore::instrument(level = "debug")]
    pub(crate) async fn update_savepoint<K, V>(
        &self,
        collection_id: Id,
        entries: &[((K, V), Timestamp, Diff)],
        upper: Option<Antichain<Timestamp>>,
    ) -> Result<(), StashError>
    where
        K: Data,
        V: Data,
    {
        let entries: Vec<_> = entries
            .into_iter()
            .map(|((key, val), time, diff)| {
                let key = key.encode_to_vec();
                let val = val.encode_to_vec();
                ((key, val), *time, *diff)
            })
            .collect();
        self.in_savepoint(|| {
            Box::pin(async { self.update(collection_id, &entries[..], upper).await })
        })
        .await
    }

    /// Directly add k, v, ts, diff tuples to a collection. `upper` can be `Some`
    /// if the collection's upper is already known. Caller must have already
    /// called in_savepoint.
    ///
    /// This function should not be called outside of the stash crate since it
    /// allows for arbitrary bytes, non-unit diffs in collections, and doesn't
    /// support transaction safety. Use `TypedCollection`'s methods instead.
    #[mz_ore::instrument(level = "debug")]
    async fn update(
        &self,
        collection_id: Id,
        entries: &[((Vec<u8>, Vec<u8>), Timestamp, Diff)],
        upper: Option<Antichain<Timestamp>>,
    ) -> Result<(), StashError> {
        {
            // Panic if the caller didn't initiate the savepoint.
            let savepoint = self.savepoint.lock().unwrap();
            assert!(*savepoint);
        }

        if entries.is_empty() {
            return Ok(());
        }

        // Check the upper in a separate future so we can issue the updates without
        // waiting for it first.
        let upper_fut = async {
            let upper = match upper {
                Some(upper) => upper,
                None => self.upper(collection_id).await?,
            };
            for ((_key, _value), time, _diff) in entries {
                if !upper.less_equal(time) {
                    return Err(StashError::from(format!(
                        "entry time {} is less than the current upper frontier {}",
                        time,
                        AntichainFormatter(&upper)
                    )));
                }
            }
            Ok(upper)
        };

        let insert_fut = async {
            let mut entries = entries.iter();
            loop {
                let mut args: Vec<&'_ (dyn ToSql + Sync)> = Vec::new();
                // All rows use the collection id, so hard code it as the first.
                args.push(&collection_id);
                let mut batch_size = 0;
                let mut estimated_json_size = 0;
                // Accumulate into a batch until the size limit is exceeded or there are no more
                // entries.
                while let Some(((key, value), time, diff)) = entries.next() {
                    estimated_json_size += key.len();
                    estimated_json_size += value.len();
                    args.push(key);
                    args.push(value);
                    args.push(time);
                    args.push(diff);
                    batch_size += 1;
                    if estimated_json_size > INSERT_BATCH_SPLIT_SIZE {
                        break;
                    }
                    if args.len() > CastFrom::cast_from(MAX_INSERT_ARGUMENTS) {
                        break;
                    }
                }
                if batch_size == 0 {
                    return Ok(());
                }
                let stmt = self.stmts.update(self.client, batch_size).await?;
                self.client.execute(&stmt, &args).await?;
            }
        };
        try_join(upper_fut, insert_fut).await?;
        Ok(())
    }

    /// Sets the since of a collection. The current upper can be `Some` if it is
    /// already known.
    #[mz_ore::instrument(level = "debug")]
    pub(crate) async fn compact<'ts>(
        &self,
        id: Id,
        new_since: &'ts Antichain<Timestamp>,
        upper: Option<Antichain<Timestamp>>,
    ) -> Result<(), StashError> {
        // Do all validation first.
        try_join(
            async move {
                let since = self.since(id).await?;
                if PartialOrder::less_than(new_since, &since) {
                    return Err(StashError::from(format!(
                        "compact request {} is less than the current since frontier {}",
                        AntichainFormatter(new_since),
                        AntichainFormatter(&since)
                    )));
                }
                Ok(())
            },
            async move {
                let upper = match upper {
                    Some(upper) => upper,
                    None => self.upper(id).await?,
                };
                if PartialOrder::less_than(&upper, new_since) {
                    return Err(StashError::from(format!(
                        "compact request {} is greater than the current upper frontier {}",
                        AntichainFormatter(new_since),
                        AntichainFormatter(&upper)
                    )));
                }
                Ok(())
            },
        )
        .await?;

        // If successful, execute the change in the txn.
        let (statement, histogram) = self.stmts.compact();
        self.client
            .execute(statement, &[&new_since.as_option(), &id])
            .map_err(StashError::from)
            .wall_time()
            .observe(histogram)
            .await?;
        maybe_update_antichain(&self.sinces, id, new_since.clone());
        Ok(())
    }

    /// Sets the upper of a collection. The current upper can be `Some` if it is
    /// already known.
    #[mz_ore::instrument(level = "debug")]
    pub(crate) async fn seal(
        &self,
        id: Id,
        new_upper: Antichain<Timestamp>,
        upper: Option<Antichain<Timestamp>>,
    ) -> Result<(), StashError> {
        let upper = match upper {
            Some(upper) => upper,
            None => self.upper(id).await?,
        };
        if PartialOrder::less_than(&new_upper, &upper) {
            return Err(StashError::from(format!(
                "seal request {} is less than the current upper frontier {}",
                AntichainFormatter(&new_upper),
                AntichainFormatter(&upper),
            )));
        }

        let (statement, histogram) = self.stmts.seal();
        self.client
            .execute(statement, &[&new_upper.as_option(), &id])
            .map_err(StashError::from)
            .wall_time()
            .observe(histogram)
            .await?;
        maybe_update_antichain(&self.uppers, id, new_upper);
        Ok(())
    }
}

/// Updates an antichain cache if the new value has advanced. Needed because the
/// functions here are often called in try_joins where the futures execute in
/// unknown order and we want to prevent a race condition poisioning the cache by
/// going backward.
fn maybe_update_antichain(
    map: &Arc<Mutex<BTreeMap<Id, Antichain<Timestamp>>>>,
    id: Id,
    updated: Antichain<Timestamp>,
) {
    match map.lock().unwrap().entry(id) {
        Entry::Occupied(mut entry) => {
            if PartialOrder::less_than(entry.get(), &updated) {
                entry.insert(updated);
            }
        }
        Entry::Vacant(entry) => {
            entry.insert(updated);
        }
    };
}