pipecircuit 0.0.19

Correct. Robust. Fast. Portable. Pick four.
Documentation
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
use super::super::inconsistency::invariant_violation;
use super::super::{
    IndexKey, WarpTable, WarpTableGetAtOutcome, WarpTableGetOutcome, WarpTableInsertWithIdOutcome,
    WarpTableRemoveOutcome, WarpTableRow,
};
use super::change::{ProjectionChange, projection_change};
use super::delivery::{FirstChange, Previous, RetainedChanges};
use super::{ObservedTable, SourceId, ViewDeliveryBuffer, ViewDeliveryError};
use super::{ViewAdmission, ViewSubscription, ViewTransmitError, ViewTransmitOutcome};
use alloc::{collections::TryReserveError, vec::Vec};
use core::num::NonZeroU64;

crate::value_wrapper! {
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    pub struct ViewId(NonZeroU64);
}

/// A deterministic, row-local selection and projection. `None` excludes a row.
/// Values must own their representation; they cannot borrow from the authority.
/// Clone and equality must preserve value semantics.
pub trait ViewDefinition<Row: WarpTableRow> {
    type Value: Clone + Eq;
    fn project(&self, row: Row::Ref<'_>) -> Option<Self::Value>;
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ViewRevision {
    pub source: SourceId,
    pub view: ViewId,
    pub epoch: u64,
    pub revision: u64,
}

#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ViewChange<Id, Value> {
    Upsert {
        id: Id,
        incarnation: u64,
        value: Value,
    },
    Remove {
        id: Id,
        incarnation: u64,
    },
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ViewRefreshOutcome {
    Unchanged,
    Published { rows: usize, changes: usize },
    Baseline { rows: usize },
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ViewRefreshError {
    WrongSource,
    RevisionExhausted,
}

#[derive(Debug)]
pub enum ViewCreationError {
    StorageUnavailable(TryReserveError),
    TableUnavailable(
        super::super::WarpTableCreationError<ViewColumnStorageError, core::convert::Infallible>,
    ),
    CapacityOverflow,
}

#[derive(Debug)]
pub struct ViewColumnStorageError {
    pub column: &'static str,
    pub source: TryReserveError,
}

pub(super) fn projected_storage<Id: IndexKey, Value>(
    capacity: super::super::Capacity,
) -> Result<WarpTable<Projected<Id, Value>>, ViewCreationError> {
    WarpTable::try_new(capacity).map_err(|error| {
        creation_error(
            error,
            |ProjectedColumnsCreationError::StorageUnavailable { column, source }| {
                ViewColumnStorageError { column, source }
            },
            |never| match never {},
        )
    })
}

pub(super) fn seen_storage<Id: IndexKey>(
    capacity: super::super::Capacity,
) -> Result<WarpTable<Seen<Id>>, ViewCreationError> {
    WarpTable::try_new(capacity).map_err(|error| {
        creation_error(
            error,
            |SeenColumnsCreationError::StorageUnavailable { column, source }| {
                ViewColumnStorageError { column, source }
            },
            |never| match never {},
        )
    })
}

pub(super) fn creation_error<Columns, Indexes>(
    error: super::super::WarpTableCreationError<Columns, Indexes>,
    columns: impl FnOnce(Columns) -> ViewColumnStorageError,
    indexes: impl FnOnce(Indexes) -> ViewCreationError,
) -> ViewCreationError {
    use super::super::WarpTableCreationError as Error;
    ViewCreationError::TableUnavailable(match error {
        Error::CapacityUnrepresentable { capacity, source } => {
            Error::CapacityUnrepresentable { capacity, source }
        }
        Error::ColumnsUnavailable { source } => Error::ColumnsUnavailable {
            source: columns(source),
        },
        Error::IndexesUnavailable { source } => return indexes(source),
        Error::IdStorageUnavailable { source } => Error::IdStorageUnavailable { source },
        Error::PrimaryIndexCapacityOverflow { maximum_rows } => {
            Error::PrimaryIndexCapacityOverflow { maximum_rows }
        }
        Error::PrimaryIndexStorageUnavailable { source } => {
            Error::PrimaryIndexStorageUnavailable { source }
        }
    })
}

pub enum ViewPublication<'view, Id, Value> {
    Baseline {
        through: ViewRevision,
        rows: &'view [ViewChange<Id, Value>],
    },
    Changes {
        base: ViewRevision,
        through: ViewRevision,
        changes: &'view [ViewChange<Id, Value>],
    },
}

pub struct ViewRow<'view, Id, Value> {
    pub id: Id,
    pub incarnation: u64,
    pub value: &'view Value,
}

pub struct ViewRows<'view, Id: IndexKey, Value> {
    inner: super::super::WarpTableRows<'view, Projected<Id, Value>>,
}

impl<'view, Id: IndexKey, Value> Iterator for ViewRows<'view, Id, Value> {
    type Item = ViewRow<'view, Id, Value>;
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|row| ViewRow {
            id: *row.id,
            incarnation: *row.incarnation,
            value: row.value,
        })
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}
impl<Id: IndexKey, Value> ExactSizeIterator for ViewRows<'_, Id, Value> {}
impl<Id: IndexKey, Value> core::iter::FusedIterator for ViewRows<'_, Id, Value> {}

pub enum ViewDelivery<'view, Id: IndexKey, Value> {
    Baseline {
        through: ViewRevision,
        rows: ViewRows<'view, Id, Value>,
    },
    Changes {
        base: ViewRevision,
        through: ViewRevision,
        changes: &'view [ViewChange<Id, Value>],
    },
    Current {
        through: ViewRevision,
    },
}

#[derive(WarpTableRow)]
#[index(primary = Id)]
pub(super) struct Projected<Id: IndexKey, Value> {
    pub(super) incarnation: u64,
    pub(super) value: Value,
    pub(super) marker: core::marker::PhantomData<Id>,
}

#[derive(WarpTableRow)]
#[index(primary = Id)]
pub(super) struct Seen<Id: IndexKey> {
    pub(super) marker: core::marker::PhantomData<Id>,
}

enum PublicationKind {
    Baseline,
    Changes { base: ViewRevision },
}

pub struct MaintainedView<Row: WarpTableRow, Definition: ViewDefinition<Row>, Brand = Row> {
    source: SourceId,
    id: ViewId,
    definition: Definition,
    epoch: u64,
    revision: u64,
    observed_through: u64,
    rows: WarpTable<Projected<Row::Id, Definition::Value>>,
    seen: WarpTable<Seen<Row::Id>>,
    pending: Vec<ViewChange<Row::Id, Definition::Value>>,
    publication: Vec<ViewChange<Row::Id, Definition::Value>>,
    kind: PublicationKind,
    history: RetainedChanges<Row::Id, Definition::Value>,
    brand: core::marker::PhantomData<fn() -> Brand>,
}

impl<Row: WarpTableRow, Brand> ObservedTable<Row, Brand> {
    pub fn maintain<Definition: ViewDefinition<Row>>(
        &self,
        id: ViewId,
        definition: Definition,
    ) -> Result<MaintainedView<Row, Definition, Brand>, ViewCreationError> {
        self.maintain_with_retention(id, definition, self.table.capacity())
    }

    pub fn maintain_with_retention<Definition: ViewDefinition<Row>>(
        &self,
        id: ViewId,
        definition: Definition,
        retained_changes: super::super::Capacity,
    ) -> Result<MaintainedView<Row, Definition, Brand>, ViewCreationError> {
        let history = RetainedChanges::try_new(retained_changes)?;
        let capacity = self.table.capacity();
        let rows = projected_storage(capacity)?;
        let seen = seen_storage(capacity)?;
        let maximum_changes = self
            .table
            .maximum_rows
            .checked_mul(2)
            .ok_or(ViewCreationError::CapacityOverflow)?;
        let mut pending = Vec::new();
        pending
            .try_reserve_exact(maximum_changes)
            .map_err(ViewCreationError::StorageUnavailable)?;
        let mut publication = Vec::new();
        publication
            .try_reserve_exact(maximum_changes)
            .map_err(ViewCreationError::StorageUnavailable)?;
        let mut view = MaintainedView {
            source: self.source,
            id,
            definition,
            epoch: 1,
            revision: 0,
            observed_through: self.sequence,
            rows,
            seen,
            pending,
            publication,
            kind: PublicationKind::Baseline,
            history,
            brand: core::marker::PhantomData,
        };
        view.prepare_baseline(self);
        view.commit(true, 0);
        Ok(view)
    }
}

impl<Row: WarpTableRow, Definition: ViewDefinition<Row>, Brand>
    MaintainedView<Row, Definition, Brand>
{
    pub const fn revision(&self) -> ViewRevision {
        ViewRevision {
            source: self.source,
            view: self.id,
            epoch: self.epoch,
            revision: self.revision,
        }
    }

    pub const fn len(&self) -> usize {
        self.rows.len()
    }
    pub const fn is_empty(&self) -> bool {
        self.rows.is_empty()
    }

    pub fn rows(&self) -> ViewRows<'_, Row::Id, Definition::Value> {
        ViewRows {
            inner: self.rows.rows(),
        }
    }

    pub fn subscribe(&self) -> ViewSubscription {
        ViewSubscription {
            source: self.source,
            view: self.id,
            cursor: None,
        }
    }

    /// Advances the subscriber only when the carrier admits an owned delivery.
    /// The callback cannot retain a borrowed projection across a later turn.
    pub fn transmit<Error>(
        &self,
        subscription: &mut ViewSubscription,
        buffer: &mut ViewDeliveryBuffer<Row::Id, Definition::Value>,
        send: impl for<'delivery> FnOnce(
            ViewDelivery<'delivery, Row::Id, Definition::Value>,
        ) -> Result<ViewAdmission, Error>,
    ) -> Result<ViewTransmitOutcome, ViewTransmitError<Error>> {
        if subscription.source != self.source || subscription.view != self.id {
            return Err(ViewTransmitError::Preparation(ViewDeliveryError::WrongView));
        }
        let delivery = self
            .delivery(subscription.cursor, buffer)
            .map_err(ViewTransmitError::Preparation)?;
        let through = self.revision();
        if let ViewDelivery::Current { .. } = delivery {
            return Ok(ViewTransmitOutcome::Current { through });
        }
        match send(delivery).map_err(ViewTransmitError::Transport)? {
            ViewAdmission::Admitted => {
                subscription.cursor = Some(through);
                Ok(ViewTransmitOutcome::Admitted { through })
            }
            ViewAdmission::Backpressured => Ok(ViewTransmitOutcome::Backpressured { through }),
        }
    }

    pub fn delivery_buffer(
        &self,
    ) -> Result<ViewDeliveryBuffer<Row::Id, Definition::Value>, ViewCreationError> {
        ViewDeliveryBuffer::try_new(self.rows.capacity(), self.history.capacity)
    }

    pub fn retained_changes(&self) -> usize {
        self.history.entries.len()
    }

    /// Coalesces against the receiver's admitted baseline, across publications.
    /// The returned borrow must be encoded or owned before the next external wait.
    pub fn delivery<'delivery>(
        &'delivery self,
        cursor: Option<ViewRevision>,
        buffer: &'delivery mut ViewDeliveryBuffer<Row::Id, Definition::Value>,
    ) -> Result<ViewDelivery<'delivery, Row::Id, Definition::Value>, ViewDeliveryError> {
        let through = self.revision();
        let Some(base) = cursor else {
            return Ok(ViewDelivery::Baseline {
                through,
                rows: self.rows(),
            });
        };
        if base.source != through.source || base.view != through.view {
            return Err(ViewDeliveryError::WrongView);
        }
        if (base.epoch, base.revision) > (through.epoch, through.revision) {
            return Err(ViewDeliveryError::FutureCursor);
        }
        if base == through {
            return Ok(ViewDelivery::Current { through });
        }
        if let PublicationKind::Changes { base: latest_base } = self.kind
            && base == latest_base
        {
            return Ok(ViewDelivery::Changes {
                base,
                through,
                changes: &self.publication,
            });
        }
        if base.epoch != through.epoch || base.revision < self.history.discarded_through {
            return Ok(ViewDelivery::Baseline {
                through,
                rows: self.rows(),
            });
        }
        if buffer.maximum_rows < self.rows.maximum_rows
            || buffer.maximum_history < self.history.maximum_changes
        {
            return Err(ViewDeliveryError::InsufficientBuffer);
        }
        clear(&mut buffer.first);
        buffer.changes.clear();
        for (index, change) in self
            .history
            .entries
            .iter()
            .enumerate()
            .rev()
            .take_while(|(_, change)| change.revision > base.revision)
        {
            match buffer.first.upsert(
                change.id,
                FirstChange {
                    index,
                    marker: core::marker::PhantomData,
                },
            ) {
                super::super::WarpTableUpsertOutcome::Inserted { .. }
                | super::super::WarpTableUpsertOutcome::Replaced { .. } => {}
                super::super::WarpTableUpsertOutcome::Full { .. } => {
                    invariant_violation("retained history exceeded delivery preparation bound")
                }
                super::super::WarpTableUpsertOutcome::UniqueConflict { conflict, .. } => {
                    match conflict {}
                }
            }
        }
        for first in buffer.first.rows() {
            let Some(previous) = self.history.entries.get(*first.index) else {
                invariant_violation("retained history disappeared during delivery")
            };
            let current = match self.rows.get(*first.id) {
                WarpTableGetOutcome::Present { row } => Some((*row.incarnation, row.value)),
                WarpTableGetOutcome::Absent { .. } => None,
            };
            match projection_change(
                previous
                    .before
                    .as_ref()
                    .map(|(incarnation, value)| (*incarnation, value)),
                current,
            ) {
                ProjectionChange::Unchanged => {}
                ProjectionChange::Upsert => {
                    let Some((incarnation, value)) = current else {
                        invariant_violation("changed projection missing")
                    };
                    buffer.changes.push(ViewChange::Upsert {
                        id: *first.id,
                        incarnation,
                        value: value.clone(),
                    });
                }
                ProjectionChange::Remove { incarnation } => {
                    buffer.changes.push(ViewChange::Remove {
                        id: *first.id,
                        incarnation,
                    })
                }
            }
        }
        Ok(ViewDelivery::Changes {
            base,
            through,
            changes: &buffer.changes,
        })
    }

    pub fn publication(&self) -> ViewPublication<'_, Row::Id, Definition::Value> {
        let through = self.revision();
        match self.kind {
            PublicationKind::Baseline => ViewPublication::Baseline {
                through,
                rows: &self.publication,
            },
            PublicationKind::Changes { base } => ViewPublication::Changes {
                base,
                through,
                changes: &self.publication,
            },
        }
    }

    pub fn refresh(
        &mut self,
        source: &ObservedTable<Row, Brand>,
    ) -> Result<ViewRefreshOutcome, ViewRefreshError> {
        Ok(self.prepare_refresh(source)?.publish())
    }

    /// Prepares a coherent cut without changing the readable publication.
    /// Prepare each participating view before publishing a multi-source cut.
    pub fn prepare_refresh(
        &mut self,
        source: &ObservedTable<Row, Brand>,
    ) -> Result<PreparedViewRefresh<'_, Row, Definition, Brand>, ViewRefreshError> {
        if self.source != source.source {
            return Err(ViewRefreshError::WrongSource);
        }
        let Some(next_revision) = self.revision.checked_add(1) else {
            return Err(ViewRefreshError::RevisionExhausted);
        };
        self.pending.clear();
        clear(&mut self.seen);
        let rebuild = self.observed_through < source.discarded_through;
        if rebuild {
            self.prepare_full_refresh(source);
        } else {
            let observed_through = self.observed_through;
            for change in source
                .history
                .iter()
                .rev()
                .take_while(|change| change.sequence > observed_through)
            {
                match self.seen.insert_with_id(
                    change.id,
                    Seen {
                        marker: core::marker::PhantomData,
                    },
                ) {
                    WarpTableInsertWithIdOutcome::Inserted { .. } => {
                        self.prepare_row(source, change.id)
                    }
                    WarpTableInsertWithIdOutcome::AlreadyPresent { .. } => {}
                    WarpTableInsertWithIdOutcome::Full { .. } => {
                        invariant_violation("bounded change history exceeded seen storage")
                    }
                    WarpTableInsertWithIdOutcome::UniqueConflict { conflict, .. } => {
                        match conflict {}
                    }
                }
            }
        }
        Ok(PreparedViewRefresh {
            view: self,
            observed_through: source.sequence,
            next_revision,
        })
    }

    pub fn replace_definition(
        &mut self,
        source: &ObservedTable<Row, Brand>,
        definition: Definition,
    ) -> Result<ViewRefreshOutcome, (Definition, ViewRefreshError)> {
        if self.source != source.source {
            return Err((definition, ViewRefreshError::WrongSource));
        }
        let Some(epoch) = self.epoch.checked_add(1) else {
            return Err((definition, ViewRefreshError::RevisionExhausted));
        };
        self.definition = definition;
        self.pending.clear();
        self.prepare_baseline(source);
        self.commit(true, 0);
        self.epoch = epoch;
        self.revision = 0;
        self.observed_through = source.sequence;
        self.kind = PublicationKind::Baseline;
        Ok(ViewRefreshOutcome::Baseline { rows: self.len() })
    }

    fn prepare_baseline(&mut self, source: &ObservedTable<Row, Brand>) {
        for ((id, incarnation), row) in source
            .table
            .ids()
            .iter()
            .zip(&source.incarnations)
            .zip(source.table.rows())
        {
            if let Some(value) = self.definition.project(row) {
                self.pending.push(ViewChange::Upsert {
                    id: *id,
                    incarnation: *incarnation,
                    value,
                });
            }
        }
    }

    fn prepare_full_refresh(&mut self, source: &ObservedTable<Row, Brand>) {
        for row in self.rows.rows() {
            if let WarpTableGetOutcome::Absent { .. } = source.table.get(*row.id) {
                self.pending.push(ViewChange::Remove {
                    id: *row.id,
                    incarnation: *row.incarnation,
                });
            }
        }
        for id in source.table.ids() {
            self.prepare_row(source, *id);
        }
    }

    fn prepare_row(&mut self, source: &ObservedTable<Row, Brand>, id: Row::Id) {
        let current = match source.table.primary_index.find(id, &source.table.ids) {
            Ok(super::super::dense_key_index::FindOutcome::Present { row, .. }) => {
                let Some(incarnation) = source.incarnations.get(row) else {
                    invariant_violation("observed incarnation missing")
                };
                let WarpTableGetAtOutcome::Present { row, .. } = source.table.get_at(row) else {
                    invariant_violation("observed row missing")
                };
                self.definition
                    .project(row)
                    .map(|value| (*incarnation, value))
            }
            Ok(super::super::dense_key_index::FindOutcome::Absent) => None,
            Err(reason) => invariant_violation(reason),
        };
        let previous = match self.rows.get(id) {
            WarpTableGetOutcome::Present { row } => Some((*row.incarnation, row.value)),
            WarpTableGetOutcome::Absent { .. } => None,
        };
        match projection_change(
            previous,
            current
                .as_ref()
                .map(|(incarnation, value)| (*incarnation, value)),
        ) {
            ProjectionChange::Unchanged => {}
            ProjectionChange::Upsert => {
                let Some((incarnation, value)) = current else {
                    invariant_violation("changed projection missing")
                };
                self.pending.push(ViewChange::Upsert {
                    id,
                    incarnation,
                    value,
                });
            }
            ProjectionChange::Remove { incarnation } => {
                self.pending.push(ViewChange::Remove { id, incarnation })
            }
        }
    }

    fn commit(&mut self, baseline: bool, revision: u64) {
        self.publication.clear();
        self.publication.extend(self.pending.iter().cloned());
        if baseline {
            clear(&mut self.rows);
            self.history.reset(revision);
        } else {
            for change in &self.pending {
                let id = match change {
                    ViewChange::Upsert { id, .. } | ViewChange::Remove { id, .. } => *id,
                };
                let before = match self.rows.get(id) {
                    WarpTableGetOutcome::Present { row } => {
                        Some((*row.incarnation, row.value.clone()))
                    }
                    WarpTableGetOutcome::Absent { .. } => None,
                };
                self.history.push(Previous {
                    revision,
                    id,
                    before,
                });
            }
        }
        for change in &self.pending {
            if let ViewChange::Remove { id, .. } = change {
                match self.rows.remove(*id) {
                    WarpTableRemoveOutcome::Removed { .. } => {}
                    WarpTableRemoveOutcome::Absent { .. } => {
                        invariant_violation("projected removal absent")
                    }
                }
            }
        }
        for change in self.pending.drain(..) {
            if let ViewChange::Upsert {
                id,
                incarnation,
                value,
            } = change
            {
                match self.rows.upsert(
                    id,
                    Projected {
                        incarnation,
                        value,
                        marker: core::marker::PhantomData,
                    },
                ) {
                    super::super::WarpTableUpsertOutcome::Inserted { .. }
                    | super::super::WarpTableUpsertOutcome::Replaced { .. } => {}
                    super::super::WarpTableUpsertOutcome::Full { .. } => {
                        invariant_violation("projection exceeded source capacity")
                    }
                    super::super::WarpTableUpsertOutcome::UniqueConflict { conflict, .. } => {
                        match conflict {}
                    }
                }
            }
        }
    }
}

/// An unpublished source cut. Dropping it leaves the last publication intact.
/// A successful preparation has no further revision or capacity refusal.
#[must_use = "publish the prepared cut or explicitly drop it to abandon it"]
pub struct PreparedViewRefresh<
    'view,
    Row: WarpTableRow,
    Definition: ViewDefinition<Row>,
    Brand = Row,
> {
    view: &'view mut MaintainedView<Row, Definition, Brand>,
    observed_through: u64,
    next_revision: u64,
}

impl<Row: WarpTableRow, Definition: ViewDefinition<Row>, Brand>
    PreparedViewRefresh<'_, Row, Definition, Brand>
{
    pub fn publish(self) -> ViewRefreshOutcome {
        let view = &mut *self.view;
        if view.pending.is_empty() {
            view.observed_through = self.observed_through;
            return ViewRefreshOutcome::Unchanged;
        }
        let base = view.revision();
        view.commit(false, self.next_revision);
        view.revision = self.next_revision;
        view.observed_through = self.observed_through;
        view.kind = PublicationKind::Changes { base };
        ViewRefreshOutcome::Published {
            rows: view.len(),
            changes: view.publication.len(),
        }
    }
}

impl<Row: WarpTableRow, Definition: ViewDefinition<Row>, Brand> Drop
    for PreparedViewRefresh<'_, Row, Definition, Brand>
{
    fn drop(&mut self) {
        self.view.pending.clear();
    }
}

pub(super) fn clear<Row: WarpTableRow>(table: &mut WarpTable<Row>) {
    while let Some(id) = table.ids().last().copied() {
        match table.remove(id) {
            WarpTableRemoveOutcome::Removed { .. } => {}
            WarpTableRemoveOutcome::Absent { .. } => {
                invariant_violation("table identity unavailable during clear")
            }
        }
    }
}