Skip to main content

mz_timely_util/
reclock.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License in the LICENSE file at the
6// root of this repository, or online at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! ## Notation
17//!
18//! Collections are represented with capital letters (T, S, R), collection traces as bold letters
19//! (𝐓, 𝐒, 𝐑), and difference traces as δ𝐓.
20//!
21//! Indexing a collection trace 𝐓 to obtain its version at `t` is written as 𝐓(t). Indexing a
22//! collection to obtain the multiplicity of a record `x` is written as T\[x\]. These can be combined
23//! to obtain the multiplicity of a record `x` at some version `t` as 𝐓(t)\[x\].
24//!
25//! ## Overview
26//!
27//! Reclocking transforms a source collection `S` that evolves with some timestamp `FromTime` into
28//! a collection `T` that evolves with some other timestamp `IntoTime`. The reclocked collection T
29//! contains all updates `u ∈ S` that are not beyond some `FromTime` frontier R(t). The collection
30//! `R` is called the remap collection.
31//!
32//! More formally, for some arbitrary time `t` of `IntoTime` and some arbitrary record `x`, the
33//! reclocked collection `T(t)[x]` is defined to be the `sum{δ𝐒(s)[x]: !(𝐑(t) βͺ― s)}`. Since this
34//! holds for any record we can write the definition of Reclock(𝐒, 𝐑) as:
35//!
36//! > Reclock(𝐒, 𝐑) β‰œ 𝐓: βˆ€ t ∈ IntoTime : 𝐓(t) = sum{δ𝐒(s): !(𝐑(t) βͺ― s)}
37//!
38//! In order for the reclocked collection `T` to have a sensible definition of progress we require
39//! that `t1 ≀ t2 β‡’ 𝐑(t1) βͺ― 𝐑(t2)` where the first `≀` is the partial order of `IntoTime` and the
40//! second one the partial order of `FromTime` antichains.
41//!
42//! ## Total order simplification
43//!
44//! In order to simplify the implementation we will require that `IntoTime` is a total order. This
45//! limitation can be lifted in the future but further elaboration on the mechanics of reclocking
46//! is required to ensure a correct implementation.
47//!
48//! ## The difference trace
49//!
50//! By the definition of difference traces we have:
51//!
52//! ```text
53//!     δ𝐓(t) = T(t) - sum{δ𝐓(s): s < t}
54//! ```
55//!
56//! Due to the total order assumption we only need to consider two cases.
57//!
58//! **Case 1:** `t` is the minimum timestamp
59//!
60//! In this case `sum{δ𝐓(s): s < t}` is the empty set and so we obtain:
61//!
62//! ```text
63//!     δ𝐓(min) = T(min) = sum{δ𝐒(s): !(𝐑(min) ≀ s}
64//! ```
65//!
66//! **Case 2:** `t` is a timestamp with a predecessor `prev`
67//!
68//! In this case `sum{δ𝐓(s): s < t}` is equal to `T(prev)` because:
69//!
70//! ```text
71//!     sum{δ𝐓(s): s < t} = sum{δ𝐓(s): s ≀ prev} + sum{δ𝐓(s): prev < s < t}
72//!                       = T(prev) + βˆ…
73//!                       = T(prev)
74//! ```
75//!
76//! And therefore the difference trace of T is:
77//!
78//! ```text
79//!     δ𝐓(t) = 𝐓(t) - 𝐓(prev)
80//!           = sum{δ𝐒(s): !(𝐑(t) βͺ― s)} - sum{δ𝐒(s): !(𝐑(prev) βͺ― s)}
81//!           = sum{δ𝐒(s): (𝐑(prev) βͺ― s) ∧ !(𝐑(t) βͺ― s)}
82//! ```
83//!
84//! ## Unique mapping property
85//!
86//! Given the definition above we can derive the fact that for any source difference δ𝐒(s) there is
87//! at most one target timestamp t that it must be reclocked to. This property can be exploited by
88//! the implementation of the operator as it can safely discard source updates once a matching
89//! Ξ΄T(t) has been found, making it "stateless" with respect to the source trace. A formal proof of
90//! this property is [provided below](#unique-mapping-property-proof).
91//!
92//! ## Operational description
93//!
94//! The operator follows a run-to-completion model where on each scheduling it completes all
95//! outstanding work that can be completed.
96//!
97//! ### Unique mapping property proof
98//!
99//! This section contains the formal proof the unique mapping property. The proof follows the
100//! structure proof notation created by Leslie Lamport. Readers unfamiliar with structured proofs
101//! can read about them here <https://lamport.azurewebsites.net/pubs/proof.pdf>.
102//!
103//! #### Statement
104//!
105//! AtMostOne(X, Ο†(x)) β‰œ βˆ€ x1, x2 ∈ X : Ο†(x1) ∧ Ο†(x2) β‡’ x1 = x2
106//!
107//! * **THEOREM** UniqueMapping β‰œ
108//!     * **ASSUME**
109//!         * **NEW** (FromTime, βͺ―) ∈ PartiallyOrderedTimestamps
110//!         * **NEW** (IntoTime, ≀) ∈ TotallyOrderedTimestamps
111//!         * **NEW** 𝐒 ∈ SetOfCollectionTraces(FromTime)
112//!         * **NEW** 𝐑 ∈ SetOfCollectionTraces(IntoTime)
113//!         * βˆ€ t ∈ IntoTime: 𝐑(t) ∈ SetOfAntichains(FromTime)
114//!         * βˆ€ t1, t1 ∈ IntoTime: t1 ≀ t2 β‡’ 𝐑(t1) βͺ― 𝐑(t2)
115//!         * **NEW** 𝐓 = Reclock(𝐒, 𝐑)
116//!     * **PROVE**  βˆ€ s ∈ FromTime : AtMostOne(IntoTime, δ𝐒(s) ∈ δ𝐓(x))
117//!
118//! #### Proof
119//!
120//! 1. **SUFFICES ASSUME** βˆƒ s ∈ FromTime: Β¬AtMostOne(IntoTime, δ𝐒(s) ∈ δ𝐓(x))
121//!     * **PROVE FALSE**
122//!     * _By proof by contradiction._
123//! 2. **PICK** s ∈ FromTime : Β¬AtMostOne(IntoTime, δ𝐒(s) ∈ δ𝐓(x))
124//!    * _Proof: Such time exists by <1>1._
125//! 3. βˆƒ t1, t2 ∈ IntoTime : t1 β‰  t2 ∧ δ𝐒(s) ∈ δ𝐓(t1) ∧ δ𝐒(s) ∈ δ𝐓(t2)
126//!     1. Β¬(βˆ€ x1, x2 ∈ X : (δ𝐒(s) ∈ δ𝐓(x1)) ∧ (δ𝐒(s) ∈ δ𝐓(x2)) β‡’ x1 = x2)
127//!         * _Proof: By <1>2 and definition of AtMostOne._
128//!     2. Q.E.D
129//!         * _Proof: By <2>1, quantifier negation rules, and theorem of propositional logic Β¬(P β‡’ Q) ≑ P ∧ Β¬Q._
130//! 4. **PICK** t1, t2 ∈ IntoTime : t1 < t2 ∧ δ𝐒(s) ∈ δ𝐓(t1) ∧ δ𝐒(s) ∈ δ𝐓(t2)
131//!    * _Proof: By <1>3. Assume t1 < t2 without loss of generality._
132//! 5. Β¬(𝐑(t1) βͺ― s)
133//!     1. **CASE** t1 = min(IntoTime)
134//!         1. δ𝐓(t1) = sum{δ𝐒(s): !(𝐑(t1)) βͺ― s}
135//!             * _Proof: By definition of δ𝐓(min)._
136//!         2. δ𝐒(s) ∈ δ𝐓(t1)
137//!             * _Proof: By <1>4._
138//!         3. Q.E.D
139//!             * _Proof: By <3>1 and <3>2._
140//!     2. **CASE** t1 > min(IntoTime)
141//!         1. **PICK** t1_prev = Predecessor(t1)
142//!             * _Proof: Predecessor exists because the set {t: t < t1} is non-empty since it must contain at least min(IntoTime)._
143//!         2. δ𝐓(t1) = sum{δ𝐒(s): (𝐑(t1_prev) βͺ― s) ∧ !(𝐑(t1) βͺ― s)}
144//!             * _Proof: By definition of δ𝐓(t)._
145//!         3. δ𝐒(s) ∈ δ𝐓(t1)
146//!             * _Proof: By <1>4._
147//!         3. Q.E.D
148//!             * _Proof: By <3>2 and <3>3._
149//!     3. Q.E.D
150//!         * _Proof: From cases <2>1 and <2>2 which are exhaustive_
151//! 6. **PICK** t2_prev ∈ IntoTime : t2_prev = Predecessor(t2)
152//!    * _Proof: Predecessor exists because by <1>4 the set {t: t < t2} is non empty since it must contain at least t1._
153//! 7. t1 ≀ t2_prev
154//!    * _Proof: t1 ∈ {t: t < t2} and t2_prev is the maximum element of the set._
155//! 8. 𝐑(t2) βͺ― s
156//!     1. t2 > min(IntoTime)
157//!         * _Proof: By <1>5._
158//!     2. **PICK** t2_prev = Predecessor(t2)
159//!         * _Proof: Predecessor exists because the set {t: t < t2} is non-empty since it must contain at least min(IntoTime)._
160//!     3. δ𝐓(t) = sum{δ𝐒(s): (𝐑(t2_prev) βͺ― s) ∧ !(𝐑(t) βͺ― s)}
161//!         * _Proof: By definition of δ𝐓(t)_
162//!     4. δ𝐒(s) ∈ δ𝐓(t1)
163//!         * _Proof: By <1>4._
164//!     5. Q.E.D
165//!         * _Proof: By <2>3 and <2>4._
166//! 9. 𝐑(t1) βͺ― 𝐑(t2_prev)
167//!     * _Proof: By <1>.7 and hypothesis on R_
168//! 10. 𝐑(t1) βͺ― s
169//!     * _Proof: By <1>8 and <1>9._
170//! 11. Q.E.D
171//!     * _Proof: By <1>5 and <1>10_
172
173use std::cmp::{Ordering, Reverse};
174use std::collections::VecDeque;
175use std::collections::binary_heap::{BinaryHeap, PeekMut};
176use std::iter::FromIterator;
177
178use differential_dataflow::difference::Semigroup;
179use differential_dataflow::lattice::Lattice;
180use differential_dataflow::{AsCollection, ExchangeData, VecCollection};
181use mz_ore::Overflowing;
182use mz_ore::collections::CollectionExt;
183use timely::communication::{Pull, Push};
184use timely::dataflow::channels::pact::Pipeline;
185use timely::dataflow::operators::CapabilitySet;
186use timely::dataflow::operators::capture::Event;
187use timely::dataflow::operators::generic::OutputBuilder;
188use timely::dataflow::operators::generic::builder_rc::OperatorBuilder;
189use timely::order::{PartialOrder, TotalOrder};
190use timely::progress::frontier::{AntichainRef, MutableAntichain};
191use timely::progress::{Antichain, Timestamp};
192
193/// Constructs an operator that reclocks a `source` collection varying with some time `FromTime`
194/// into the corresponding `reclocked` collection varying over some time `IntoTime` using the
195/// provided `remap` collection.
196///
197/// In order for the operator to read the `source` collection a `Pusher` is returned which can be
198/// used with timely's capture facilities to connect a collection from a foreign scope to this
199/// operator.
200pub fn reclock<'scope, D, FromTime, IntoTime, R>(
201    remap_collection: VecCollection<'scope, IntoTime, FromTime, Overflowing<i64>>,
202    as_of: Antichain<IntoTime>,
203) -> (
204    Box<dyn Push<Event<FromTime, Vec<(D, FromTime, R)>>>>,
205    VecCollection<'scope, IntoTime, D, R>,
206)
207where
208    D: ExchangeData,
209    FromTime: Timestamp,
210    IntoTime: Timestamp + Lattice + TotalOrder,
211    R: Semigroup + 'static,
212{
213    let scope = remap_collection.scope();
214    let mut builder = OperatorBuilder::new("Reclock".into(), scope.clone());
215    // Here we create a channel that can be used to send data from a foreign scope into this
216    // operator. The channel is associated with this operator's address so that it is activated
217    // every time events are available for consumption. This mechanism is similar to Timely's input
218    // handles where data can be introduced into a timely scope from an exogenous source.
219    let info = builder.operator_info();
220    let channel_id = scope.worker().new_identifier();
221    let (pusher, mut events) = scope
222        .worker()
223        .pipeline::<Event<FromTime, Vec<(D, FromTime, R)>>>(channel_id, info.address);
224
225    let mut remap_input = builder.new_input(remap_collection.inner, Pipeline);
226    // Keep the output disconnected from the remap collection input so that we can drop the output
227    // capability when we finish reclocking the source, which can happen before the
228    // remap_collection reaches the input frontier. See the `test_finalized_source` for an example.
229    let (output, reclocked) = builder.new_output_connection([]);
230    let mut output = OutputBuilder::from(output);
231
232    builder.build(move |caps| {
233        let mut capset = CapabilitySet::from_elem(caps.into_element());
234        capset.downgrade(&as_of.borrow());
235
236        // Received remap updates at times `into_time` greater or equal to `remap_input`'s input
237        // frontier. As the input frontier advances, we drop elements out of this priority queue
238        // and mint new associations.
239        let mut pending_remap: BinaryHeap<Reverse<(IntoTime, FromTime, i64)>> = BinaryHeap::new();
240        // The bindings of `remap_input` at times beyond its since and not beyond the input
241        // frontier.
242        let mut remap_trace = RemapTrace::new(as_of.clone());
243
244        // A stash of source updates for which we don't know the corresponding binding yet.
245        let mut deferred_source_updates: Vec<ChainBatch<_, _, _>> = Vec::new();
246        // The frontier of the `events` input
247        let mut source_frontier = MutableAntichain::from_elem(FromTime::minimum());
248
249        // Accumulation buffer for `remap_input` updates.
250        use timely::progress::ChangeBatch;
251        let mut remap_accum_buffer: ChangeBatch<(IntoTime, FromTime)> = ChangeBatch::new();
252
253        // The operator drains `remap_input` and organizes new bindings that are not beyond
254        // `remap_input`'s frontier into the time ordered `remap_trace`.
255        //
256        // All received data events can either be reclocked to a time included in the
257        // `remap_trace`, or deferred until new associations are minted. Each data event that
258        // happens at some `FromTime` is mapped to the first `IntoTime` whose associated antichain
259        // is not less or equal to the input `FromTime`.
260        //
261        // As progress events are received from the `events` input, we can advance our
262        // held capability to track the least `IntoTime` a newly received `FromTime` could possibly
263        // map to and also compact the maintained `remap_trace` to that time.
264        move |frontiers| {
265            let Some(cap) = capset.get(0).cloned() else {
266                remap_input.for_each(|_, _| {});
267                return;
268            };
269            let mut output = output.activate();
270            let mut session = output.session(&cap);
271
272            // STEP 1. Accept new bindings into `pending_remap`.
273            // Advance all `into` times by `as_of`, and consolidate all updates at that frontier.
274            remap_input.for_each(|_, data| {
275                for (from, mut into, diff) in data.drain(..) {
276                    into.advance_by(as_of.borrow());
277                    remap_accum_buffer.update((into, from), diff.into_inner());
278                }
279            });
280            // Drain consolidated bindings into the `pending_remap` heap.
281            // Only do this once any of the `remap_input` frontier has passed `as_of`.
282            // For as long as the input frontier is less-equal `as_of`, we have no finalized times.
283            if !PartialOrder::less_equal(&frontiers[0].frontier(), &as_of.borrow()) {
284                // Taking the buffer releases its capacity. A replay of the remap history from an
285                // old as-of fills it once, and every export's operator would hold that capacity
286                // for good.
287                for ((into, from), diff) in std::mem::take(&mut remap_accum_buffer).into_inner() {
288                    pending_remap.push(Reverse((into, from, diff)));
289                }
290            }
291
292            // STEP 2. Extract bindings not beyond `remap_frontier` and commit them into `remap_trace`.
293            let remap_upper = frontiers[0].frontier().to_owned();
294            while let Some(Reverse((into, _, _))) = pending_remap.peek()
295                && !remap_upper.less_equal(into)
296            {
297                // The heap yields the updates of a time together, and all of them are in it
298                // because the remap frontier has passed that time.
299                let into = into.clone();
300                let updates = std::iter::from_fn(|| {
301                    let update = pending_remap.peek_mut()?;
302                    (update.0.0 == into).then(|| {
303                        let Reverse((_, from, diff)) = PeekMut::pop(update);
304                        (from, diff)
305                    })
306                });
307                remap_trace.push(into.clone(), updates);
308            }
309            // Releases what a replay leaves behind, like `remap_accum_buffer` above.
310            if pending_remap.len() < pending_remap.capacity() / 4 {
311                pending_remap.shrink_to(pending_remap.len() * 2);
312            }
313
314            // STEP 3. Receive new data updates
315            //         The `events` input describes arbitrary progress and data over `FromTime`,
316            //         which must be translated to `IntoTime`. Each `FromTime` can be found as the
317            //         first `IntoTime` associated with a `[FromTime]` that is not less or equal to
318            //         the input `FromTime`. Received events that are not yet associated to an
319            //         `IntoTime` are collected, and formed into a "chain batch": a sequence of
320            //         chains that results from sorting the updates by `FromTime`, and then
321            //         segmenting the sequence at elements where the partial order on `FromTime` is
322            //         violated.
323            let mut stash = Vec::new();
324            // Consolidate progress updates before applying them to `source_frontier`, to avoid quadratic
325            // behavior in overload scenarios.
326            let mut change_batch = ChangeBatch::<FromTime, 2>::default();
327            while let Some(event) = events.pull() {
328                match event {
329                    Event::Progress(changes) => {
330                        change_batch.extend(changes.drain(..));
331                    }
332                    Event::Messages(_, data) => stash.append(data),
333                }
334            }
335            source_frontier.update_iter(change_batch.drain());
336            stash.sort_unstable_by(|(_, t1, _): &(D, FromTime, R), (_, t2, _)| t1.cmp(t2));
337            let mut new_source_updates = ChainBatch::from_iter(stash);
338
339            // STEP 4: Reclock the source frontier and the new and deferred updates
340            //         This only makes sense if there are any times for which we can correctly
341            //         accumulate the remap trace, which is what we check here.
342            //
343            // NOTE: `less_than` is false for an empty since. That can't happen here. Step 5
344            // empties the since and the capability set together, and the operator returns early
345            // once it holds no capability.
346            if PartialOrder::less_than(remap_trace.since(), &remap_upper) {
347                // 4.1. Reclock `source_frontier`
348                //      If any FromTime in the source frontier could still be reclocked to a
349                //      binding then we must keep our capability to emit data at that binding's
350                //      time and not compact past it. Without such a binding the frontier maps to
351                //      `remap_upper`.
352                let source_frontier = source_frontier.frontier();
353                let reclocked_source_frontier = match remap_trace
354                    .cursor()
355                    .seek(|bound| !PartialOrder::less_equal(&bound, &source_frontier))
356                {
357                    Some((time, _)) => Antichain::from_elem(time.clone()),
358                    None => remap_upper.clone(),
359                };
360
361                // 4.2. Extract updates from `new_source_updates` and `deferred_source_updates`
362                //      The cursor stops only at bindings that some pending update maps to, and
363                //      each stop extracts every update that maps there.
364                let mut cursor = remap_trace.cursor();
365                while !(new_source_updates.is_empty() && deferred_source_updates.is_empty())
366                    && let Some((cur_time, cur_frontier)) = cursor.seek(|frontier| {
367                        new_source_updates.can_extract(frontier)
368                            || deferred_source_updates
369                                .iter()
370                                .any(|batch| batch.can_extract(frontier))
371                    })
372                {
373                    for (data, _, diff) in new_source_updates.extract(cur_frontier) {
374                        session.give((data, cur_time.clone(), diff));
375                    }
376                    deferred_source_updates.retain_mut(|batch| {
377                        for (data, _, diff) in batch.extract(cur_frontier) {
378                            session.give((data, cur_time.clone(), diff));
379                        }
380                        // Retain non-empty batches
381                        !batch.is_empty()
382                    });
383                }
384
385                // STEP 5. Downgrade capability and compact remap trace if our since frontier
386                //         advanced
387                if PartialOrder::less_than(remap_trace.since(), &reclocked_source_frontier) {
388                    capset.downgrade(&reclocked_source_frontier.borrow());
389                    remap_trace.advance_since(reclocked_source_frontier);
390                }
391            }
392
393            // STEP 6. Tidy up deferred updates
394            //         Deferred updates are represented as a list of chain batches where each batch
395            //         contains two times the updates of the batch proceeding it. This organization
396            //         leads to a logarithmic number of batches with respect to the outstanding
397            //         number of updates.
398            deferred_source_updates.sort_unstable_by_key(|b| Reverse(b.len()));
399            if !new_source_updates.is_empty() {
400                deferred_source_updates.push(new_source_updates);
401            }
402            let dsu = &mut deferred_source_updates;
403            while dsu.len() > 1 && (dsu[dsu.len() - 1].len() >= dsu[dsu.len() - 2].len() / 2) {
404                let a = dsu.pop().unwrap();
405                let b = dsu.pop().unwrap();
406                dsu.push(a.merge_with(b));
407            }
408
409            // If using less than a quarter of the capacity, shrink the container. To avoid having
410            // to resize the container on a subsequent push, shrink to 2x the length, which is
411            // what push would grow it to.
412            if deferred_source_updates.len() < deferred_source_updates.capacity() / 4 {
413                deferred_source_updates.shrink_to(deferred_source_updates.len() * 2);
414            }
415
416            // If this condition holds then this operator has no more work to do, so we drop the capability.
417            if source_frontier.frontier().is_empty() && deferred_source_updates.is_empty() {
418                capset = CapabilitySet::new();
419            }
420        }
421    });
422
423    (Box::new(pusher), reclocked.as_collection())
424}
425
426/// A batch of differential updates that vary over some partial order. This type maintains the data
427/// as a set of chains that allows for efficient extraction of batches given a frontier.
428#[derive(Debug, PartialEq)]
429struct ChainBatch<D, T, R> {
430    /// A list of chains (sets of mutually comparable times) sorted by the partial order.
431    chains: Vec<VecDeque<(D, T, R)>>,
432}
433
434impl<D, T: Timestamp, R> ChainBatch<D, T, R> {
435    /// Extracts all updates with time not greater or equal to any time in `upper`.
436    fn extract<'a>(
437        &'a mut self,
438        upper: AntichainRef<'a, T>,
439    ) -> impl Iterator<Item = (D, T, R)> + 'a {
440        self.chains.retain(|chain| !chain.is_empty());
441        self.chains.iter_mut().flat_map(move |chain| {
442            // A chain is a sorted list of mutually comparable elements so we keep extracting
443            // elements that are not beyond upper.
444            std::iter::from_fn(move || {
445                let (_, into, _) = chain.front()?;
446                if !upper.less_equal(into) {
447                    chain.pop_front()
448                } else {
449                    None
450                }
451            })
452        })
453    }
454
455    /// Returns whether [`Self::extract`] would extract any update for `upper`.
456    fn can_extract(&self, upper: AntichainRef<'_, T>) -> bool {
457        self.chains
458            .iter()
459            .any(|chain| chain.front().is_some_and(|(_, t, _)| !upper.less_equal(t)))
460    }
461
462    fn merge_with(
463        mut self: ChainBatch<D, T, R>,
464        mut other: ChainBatch<D, T, R>,
465    ) -> ChainBatch<D, T, R>
466    where
467        D: ExchangeData,
468        T: Timestamp,
469        R: Semigroup,
470    {
471        let mut updates1 = self.chains.drain(..).flatten().peekable();
472        let mut updates2 = other.chains.drain(..).flatten().peekable();
473
474        let merged = std::iter::from_fn(|| {
475            match (updates1.peek(), updates2.peek()) {
476                (Some((d1, t1, _)), Some((d2, t2, _))) => {
477                    match (t1, d1).cmp(&(t2, d2)) {
478                        Ordering::Less => updates1.next(),
479                        Ordering::Greater => updates2.next(),
480                        // If the same (d, t) pair is found, consolidate their diffs
481                        Ordering::Equal => {
482                            let (d1, t1, mut r1) = updates1.next().unwrap();
483                            while let Some((_, _, r)) =
484                                updates1.next_if(|(d, t, _)| (d, t) == (&d1, &t1))
485                            {
486                                r1.plus_equals(&r);
487                            }
488                            while let Some((_, _, r)) =
489                                updates2.next_if(|(d, t, _)| (d, t) == (&d1, &t1))
490                            {
491                                r1.plus_equals(&r);
492                            }
493                            Some((d1, t1, r1))
494                        }
495                    }
496                }
497                (Some(_), None) => updates1.next(),
498                (None, Some(_)) => updates2.next(),
499                (None, None) => None,
500            }
501        });
502
503        ChainBatch::from_iter(merged.filter(|(_, _, r)| !r.is_zero()))
504    }
505
506    /// Returns the number of updates in the batch.
507    fn len(&self) -> usize {
508        self.chains.iter().map(|chain| chain.len()).sum()
509    }
510
511    /// Returns true if the batch contains no updates.
512    fn is_empty(&self) -> bool {
513        self.len() == 0
514    }
515}
516
517impl<D, T: Timestamp, R> FromIterator<(D, T, R)> for ChainBatch<D, T, R> {
518    /// Computes the chain decomposition of updates according to the partial order `T`.
519    fn from_iter<I: IntoIterator<Item = (D, T, R)>>(updates: I) -> Self {
520        let mut chains = vec![];
521        let mut updates = updates.into_iter();
522        if let Some((d, t, r)) = updates.next() {
523            let mut chain = VecDeque::new();
524            chain.push_back((d, t, r));
525            for (d, t, r) in updates {
526                let prev_t = &chain[chain.len() - 1].1;
527                if !PartialOrder::less_equal(prev_t, &t) {
528                    chains.push(chain);
529                    chain = VecDeque::new();
530                }
531                chain.push_back((d, t, r));
532            }
533            chains.push(chain);
534        }
535        Self { chains }
536    }
537}
538
539/// The bindings of a remap collection at its since and at every later time that has an update.
540///
541/// Reclocking a `FromTime` means finding the first binding that is not less or equal to it.
542/// Bindings only advance with time (see the module docs). The trace stores some bindings whole, as
543/// keyframes, and the updates at the times between them. [`Cursor::seek`] binary searches the
544/// keyframes and applies the updates after the last one the predicate fails for.
545///
546/// This approach strikes a balance between updates and materialized antichains to improve the
547/// performance of reclock while limiting memory usage. This is most often an issue when snapshot
548/// and CDC run concurrently. A snapshotting export holds back the since, resulting in a
549/// trace that gradually accumulates updates over time. CDC events map to the newest bindings.
550/// With only updates stored, finding those means summing across the majority of the trace.
551///
552/// At the other extreme, materializing the frontier at every time requires memory proportional
553/// to the antichain width for each time. This ends up consuming memory for elements that may not
554/// have changed (for example UUIDs of GTID set that are no longer written to). Historically,
555/// this memory intensive approach was dropped.
556struct RemapTrace<FromTime, IntoTime> {
557    /// When non-empty, this equals `keyframes[0].time`. It becomes empty after the remap input
558    /// closes. `keyframes[0].time` can't show that, because `advance_by` with an empty frontier
559    /// leaves a time unchanged.
560    since: Antichain<IntoTime>,
561    /// In strictly increasing time order. Never empty, and the first is the binding at the since.
562    keyframes: VecDeque<Keyframe<FromTime, IntoTime>>,
563    /// The updates between keyframes and after the last one, in time order. Updates at a
564    /// keyframe's time are applied to that keyframe and not stored here.
565    updates: VecDeque<(FromTime, IntoTime, i64)>,
566    /// The number of updates pushed since the last keyframe was created, including the ones
567    /// applied to it.
568    run: usize,
569    /// Working space for [`updated`]. It keeps its buffers between uses.
570    scratch: MutableAntichain<FromTime>,
571}
572
573/// A binding that a [`RemapTrace`] stores whole.
574#[derive(Debug, Clone, PartialEq)]
575struct Keyframe<FromTime, IntoTime> {
576    time: IntoTime,
577    /// The frontier of the remap collection at `time`.
578    frontier: Antichain<FromTime>,
579}
580
581/// Returns the frontier that `frontier` becomes when `updates` are applied to it. `scratch` may
582/// hold anything, and is left holding the result.
583fn updated<T: Timestamp>(
584    scratch: &mut MutableAntichain<T>,
585    frontier: &Antichain<T>,
586    updates: impl IntoIterator<Item = (T, i64)>,
587) -> Antichain<T> {
588    // TODO: A `MutableAntichain` does more work than the trace needs. A sorted vector of
589    // elements, where each update inserts or removes one, could replace it. It does two things
590    // that reclock can assume away, because the module docs require 𝐑(t) to be an antichain.
591    //
592    // * It counts how many times each element was added. The remap collection holds every
593    //   element once.
594    // * It works out the minimal elements again whenever an update touches the frontier, by
595    //   comparing elements with each other. Every element the remap collection holds at a time
596    //   is minimal.
597    //
598    // The `reclock_sparse_gtid_10_uuids` bench measured 3.0 ms at 100,000 bindings this way,
599    // against 0.59 ms with sorted vectors.
600    scratch.clear();
601    scratch.update_iter(
602        frontier
603            .iter()
604            .cloned()
605            .map(|from| (from, 1))
606            .chain(updates),
607    );
608    // The result keeps only the minimal elements. An element that is not minimal would be
609    // dropped here, and lost for good once the element below it is retracted. The counts are
610    // exactly the frontier when no such element exists and none is held twice.
611    let (elements, once) = scratch
612        .updates()
613        .fold((0, true), |(elements, once), (_, count)| {
614            (elements + 1, once && *count == 1)
615        });
616    assert!(
617        once && elements == scratch.frontier().len(),
618        "the remap collection must be an antichain at every time"
619    );
620    scratch.frontier().to_owned()
621}
622
623impl<FromTime, IntoTime> RemapTrace<FromTime, IntoTime>
624where
625    FromTime: Timestamp,
626    IntoTime: Timestamp + Lattice + TotalOrder,
627{
628    /// Returns a trace whose frontier at `since` is empty, until updates arrive at that time.
629    fn new(since: Antichain<IntoTime>) -> Self {
630        let mut time = IntoTime::minimum();
631        time.advance_by(since.borrow());
632        Self {
633            since,
634            keyframes: VecDeque::from([Keyframe {
635                time,
636                frontier: Antichain::new(),
637            }]),
638            updates: VecDeque::new(),
639            run: 0,
640            scratch: MutableAntichain::new(),
641        }
642    }
643
644    fn since(&self) -> &Antichain<IntoTime> {
645        &self.since
646    }
647
648    /// Applies the updates of time `into`. Every time must be pushed once, with all its updates,
649    /// in time order and not before the since.
650    fn push(&mut self, into: IntoTime, updates: impl IntoIterator<Item = (FromTime, i64)>) {
651        let Keyframe {
652            time: key_time,
653            frontier: key_frontier,
654        } = self
655            .keyframes
656            .back()
657            .expect("the trace holds the binding at the since");
658
659        // The last update, if it lies after the last keyframe.
660        let after_keyframe = self.updates.back().filter(|(_, time, _)| key_time < time);
661
662        // invariant: times arrive in order. Only the since can be pushed at the time of a
663        // keyframe, which stands there before the since has updates of its own.
664        let in_order = match after_keyframe {
665            Some((_, time, _)) => *time < into,
666            None => *key_time <= into,
667        };
668        assert!(in_order, "remap updates out of time order");
669
670        let mut count = 0;
671        let updates = updates.into_iter().inspect(|_| count += 1);
672        if *key_time == into {
673            let Keyframe {
674                frontier: key_frontier,
675                ..
676            } = self
677                .keyframes
678                .back_mut()
679                .expect("the trace holds the binding at the since");
680            *key_frontier = updated(&mut self.scratch, key_frontier, updates);
681        } else if self.run >= key_frontier.len() {
682            // A keyframe is a materialized antichain, consuming memory proportional to its width.
683            // This creates a keyframe based on the number of updates that have arrived since
684            // the last keyframe. If most of the elements end up changing, this results in storing
685            // a keyframe for each time. The expectation is that there are many updates being
686            // made, in which case this trades memory for speed.
687            //
688            // A Kafka source doesn't run concurrent snapshot and CDC, so its trace is going to
689            // remain relatively small and this extra space isn't much of a concern. A MySQL source
690            // is more likely to see an increase in memory usage where the GTID set contains many
691            // UUIDs that are all advancing (e.g. multi-master setup, where MZ reads from the
692            // replica).
693            let start = self
694                .updates
695                .partition_point(|(_, time, _)| time <= key_time);
696            let frontier = updated(
697                &mut self.scratch,
698                key_frontier,
699                self.updates
700                    .range(start..)
701                    .map(|(from, _, diff)| (from.clone(), *diff))
702                    .chain(updates),
703            );
704            self.keyframes.push_back(Keyframe {
705                time: into,
706                frontier,
707            });
708            self.run = 0;
709        } else {
710            self.updates
711                .extend(updates.map(|(from, diff)| (from, into.clone(), diff)));
712        }
713        self.run += count;
714    }
715
716    /// Advances the since to `since`, which must not be behind it, and drops the bindings before
717    /// it.
718    fn advance_since(&mut self, since: Antichain<IntoTime>) {
719        // The binding at the since is the last keyframe at or before it, with the updates up to
720        // the since applied.
721        while self
722            .keyframes
723            .get(1)
724            .is_some_and(|keyframe| !since.less_than(&keyframe.time))
725        {
726            self.keyframes.pop_front();
727        }
728        let Keyframe {
729            time: key_time,
730            frontier: key_frontier,
731        } = self
732            .keyframes
733            .front_mut()
734            .expect("the trace holds the binding at the since");
735        while self
736            .updates
737            .front()
738            .is_some_and(|(_, time, _)| time < key_time)
739        {
740            self.updates.pop_front();
741        }
742        let folded = self
743            .updates
744            .partition_point(|(_, time, _)| !since.less_than(time));
745        if folded > 0 {
746            *key_frontier = updated(
747                &mut self.scratch,
748                key_frontier,
749                self.updates
750                    .drain(..folded)
751                    .map(|(from, _, diff)| (from, diff)),
752            );
753        }
754        key_time.advance_by(since.borrow());
755        shrink(&mut self.keyframes);
756        shrink(&mut self.updates);
757        self.since = since;
758    }
759
760    /// Returns a cursor before the binding at the since.
761    fn cursor(&self) -> Cursor<'_, FromTime, IntoTime> {
762        Cursor {
763            trace: self,
764            keyframe_pos: None,
765            update_pos: 0,
766            frontier: MutableAntichain::new(),
767        }
768    }
769}
770
771/// A position in a [`RemapTrace`] that only moves forward.
772struct Cursor<'a, FromTime, IntoTime> {
773    trace: &'a RemapTrace<FromTime, IntoTime>,
774    /// The index of the last keyframe at or before the cursor. `None` before the since.
775    keyframe_pos: Option<usize>,
776    /// The index of the first update after the cursor.
777    update_pos: usize,
778    /// The frontier at the cursor, when that lies between keyframes. It keeps its buffers as the
779    /// cursor moves.
780    frontier: MutableAntichain<FromTime>,
781}
782
783impl<'a, FromTime, IntoTime> Cursor<'a, FromTime, IntoTime>
784where
785    FromTime: Timestamp,
786    IntoTime: Timestamp + Lattice + TotalOrder,
787{
788    /// Moves to the first binding after the cursor that satisfies `pred`, and returns that
789    /// binding with its time. Returns `None` if there is none.
790    ///
791    /// Once `pred` holds for a binding it must hold for every later binding.
792    fn seek(
793        &mut self,
794        mut pred: impl FnMut(AntichainRef<'_, FromTime>) -> bool,
795    ) -> Option<(&'a IntoTime, AntichainRef<'_, FromTime>)> {
796        let RemapTrace {
797            keyframes, updates, ..
798        } = self.trace;
799
800        // Starting point for the seek.
801        let start_pos = self.keyframe_pos.map_or(0, |keyframe| keyframe + 1);
802
803        // Finds the first keyframe after the cursor's current keyframe position that satisfies
804        // `pred`. If none does, `found_pos` is one past the last keyframe. The binding sought is
805        // either that keyframe or lies between it and the keyframe before it.
806        let found_pos = match keyframes.get(start_pos) {
807            Some(next) if !pred(next.frontier.borrow()) => keyframes.partition_point(|keyframe| {
808                keyframe.time <= next.time || !pred(keyframe.frontier.borrow())
809            }),
810            _ => start_pos,
811        };
812        // Jump to the keyframe before `found_pos` and step forward from there, stopping at
813        // `found_pos`.
814        if let Some(prev_pos) = found_pos.checked_sub(1)
815            && self
816                .keyframe_pos
817                .is_none_or(|keyframe_pos| keyframe_pos < prev_pos)
818        {
819            let time = &keyframes[prev_pos].time;
820            self.keyframe_pos = Some(prev_pos);
821            self.update_pos = updates.partition_point(|(_, t, _)| t <= time);
822        }
823        while self.step() {
824            let keyframe = self.keyframe_pos.expect("the cursor stepped");
825            let at_found = keyframe == found_pos && !self.between();
826            if at_found || pred(self.current().1) {
827                return Some(self.current());
828            }
829        }
830        None
831    }
832
833    /// Moves to the next binding. Returns false at the end of the trace.
834    fn step(&mut self) -> bool {
835        let RemapTrace {
836            keyframes, updates, ..
837        } = self.trace;
838        let Some(keyframe_pos) = self.keyframe_pos else {
839            // Every update lies after the first keyframe, which `update_pos` already says.
840            self.keyframe_pos = Some(0);
841            return true;
842        };
843        let next_keyframe_pos = keyframes.get(keyframe_pos + 1);
844        match updates.get(self.update_pos) {
845            Some((_, time, _)) if next_keyframe_pos.is_none_or(|next| time < &next.time) => {
846                let end = self.update_pos
847                    + updates
848                        .range(self.update_pos..)
849                        .take_while(|(_, t, _)| t == time)
850                        .count();
851                let tick = updates
852                    .range(self.update_pos..end)
853                    .map(|(from, _, diff)| (from.clone(), *diff));
854                if self.between() {
855                    self.frontier.update_iter(tick);
856                } else {
857                    // The cursor leaves its keyframe. Seeding the frontier with the keyframe's
858                    // elements in the same call as the updates works it out once.
859                    let seed = keyframes[keyframe_pos]
860                        .frontier
861                        .iter()
862                        .cloned()
863                        .map(|from| (from, 1));
864                    self.frontier.clear();
865                    self.frontier.update_iter(seed.chain(tick));
866                }
867                self.update_pos = end;
868                true
869            }
870            _ if next_keyframe_pos.is_some() => {
871                self.keyframe_pos = Some(keyframe_pos + 1);
872                true
873            }
874            _ => false,
875        }
876    }
877
878    /// Returns whether the cursor has stepped past its keyframe onto a time that only has
879    /// updates. Returns false before the since.
880    ///
881    /// When this is true, the frontier at the cursor is in `self.frontier`. When it is false, the
882    /// cursor sits on the keyframe and the frontier is the keyframe's frontier.
883    fn between(&self) -> bool {
884        let RemapTrace {
885            keyframes, updates, ..
886        } = self.trace;
887        let (Some(keyframe_pos), Some(update_pos)) =
888            (self.keyframe_pos, self.update_pos.checked_sub(1))
889        else {
890            return false;
891        };
892        // `update_pos` is the position of the last update the cursor consumed. Its time tells
893        // where the cursor is relative to the keyframe.
894        //
895        // * A later time means the cursor consumed that update after it reached the keyframe. It
896        //   has moved past the keyframe.
897        // * An earlier time means the cursor consumed that update on its way to the keyframe, and
898        //   nothing since. It still sits on the keyframe.
899        //
900        // The times cannot be equal. The updates at a keyframe's time are part of the keyframe
901        // and never appear in `updates`.
902        updates[update_pos].1 > keyframes[keyframe_pos].time
903    }
904
905    /// Returns the time and frontier at the cursor, which must not be before the since.
906    fn current(&self) -> (&'a IntoTime, AntichainRef<'_, FromTime>) {
907        let keyframe_pos = self.keyframe_pos.expect("the cursor is past the since");
908        let RemapTrace {
909            keyframes, updates, ..
910        } = self.trace;
911        if self.between() {
912            let (_, time, _) = &updates[self.update_pos - 1];
913            (time, self.frontier.frontier())
914        } else {
915            let Keyframe { time, frontier } = &keyframes[keyframe_pos];
916            (time, frontier.borrow())
917        }
918    }
919}
920
921/// Shrinks `deque` if it uses less than a quarter of its capacity. It keeps twice the length,
922/// which is what a push would grow it to.
923fn shrink<T>(deque: &mut VecDeque<T>) {
924    if deque.len() < deque.capacity() / 4 {
925        deque.shrink_to(deque.len() * 2);
926    }
927}
928
929#[cfg(test)]
930mod test {
931    use std::collections::BTreeMap;
932    use std::sync::atomic::AtomicUsize;
933    use std::sync::mpsc::{Receiver, TryRecvError};
934
935    use differential_dataflow::consolidation;
936    use differential_dataflow::input::{Input, InputSession};
937    use mz_ore::cast::CastFrom;
938    use serde::{Deserialize, Serialize};
939    use timely::dataflow::operators::capture::{Event, Extract};
940    use timely::dataflow::operators::vec::UnorderedInput;
941    use timely::dataflow::operators::vec::unordered_input::UnorderedHandle;
942    use timely::dataflow::operators::{ActivateCapability, Capture};
943    use timely::progress::timestamp::Refines;
944    use timely::progress::{PathSummary, Stamp};
945    use timely::worker::Worker;
946
947    use crate::capture::PusherCapture;
948    use crate::order::Partitioned;
949
950    use super::*;
951
952    type Diff = Overflowing<i64>;
953    type FromTime = Partitioned<u64, u64>;
954    type IntoTime = u64;
955    type BindingHandle<FromTime> = InputSession<IntoTime, FromTime, Diff>;
956    type DataHandle<D, FromTime> = (
957        UnorderedHandle<FromTime, (D, FromTime, Diff)>,
958        ActivateCapability<FromTime>,
959    );
960    type ReclockedStream<D> = Receiver<Event<IntoTime, Vec<(D, IntoTime, Diff)>>>;
961
962    /// A helper function that sets up a dataflow program to test the reclocking operator. Each
963    /// test provides a test logic closure which accepts four arguments:
964    ///
965    /// * A reference to the worker that allows the test to step the computation
966    /// * A [`BindingHandle`] that allows the test to manipulate the remap bindings
967    /// * A [`DataHandle`] that allows the test to submit the data to be reclocked
968    /// * A [`ReclockedStream`] that allows observing the result of the reclocking process
969    ///
970    /// Note that the `DataHandle` contains a capability that should be dropped or downgraded before
971    /// calling [`step`] to process data at the time.
972    fn harness<FromTime, D, F, R>(as_of: Antichain<IntoTime>, test_logic: F) -> R
973    where
974        FromTime: Timestamp + Refines<()>,
975        D: ExchangeData,
976        F: FnOnce(
977                &mut Worker,
978                BindingHandle<FromTime>,
979                DataHandle<D, FromTime>,
980                ReclockedStream<D>,
981            ) -> R
982            + Send
983            + Sync
984            + 'static,
985        R: Send + 'static,
986    {
987        timely::execute_directly(move |worker| {
988            let (bindings, data, data_cap, reclocked) = worker.dataflow::<(), _, _>(|scope| {
989                let (bindings, data_pusher, reclocked) =
990                    scope.scoped::<IntoTime, _, _>("IntoScope", move |scope| {
991                        let (binding_handle, binding_collection) = scope.new_collection();
992                        let (data_pusher, reclocked_collection) =
993                            reclock(binding_collection, as_of);
994                        let reclocked_capture = reclocked_collection.inner.capture();
995                        (binding_handle, data_pusher, reclocked_capture)
996                    });
997
998                let (data, data_cap) = scope.scoped::<FromTime, _, _>("FromScope", move |scope| {
999                    let ((handle, cap), data) = scope.new_unordered_input::<(D, FromTime, Diff)>();
1000                    data.capture_into(PusherCapture(data_pusher));
1001                    (handle, cap)
1002                });
1003
1004                (bindings, data, data_cap, reclocked)
1005            });
1006
1007            test_logic(worker, bindings, (data, data_cap), reclocked)
1008        })
1009    }
1010
1011    /// Steps the worker four times which is the required number of times for both data and
1012    /// frontier updates to propagate across the two scopes and into the probing channels.
1013    fn step(worker: &mut Worker) {
1014        for _ in 0..4 {
1015            worker.step();
1016        }
1017    }
1018
1019    #[mz_ore::test]
1020    fn basic_reclocking() {
1021        let as_of = Antichain::from_elem(IntoTime::minimum());
1022        harness::<FromTime, _, _, _>(
1023            as_of,
1024            |worker, bindings, (mut data, data_cap), reclocked| {
1025                // Reclock everything at the minimum IntoTime
1026                bindings.close();
1027                data.activate()
1028                    .session(&data_cap)
1029                    .give(('a', Partitioned::minimum(), Diff::ONE));
1030                drop(data_cap);
1031                step(worker);
1032                let extracted = reclocked.extract();
1033                let expected = vec![(0, vec![('a', 0, Diff::ONE)])];
1034                assert_eq!(extracted, expected);
1035            },
1036        )
1037    }
1038
1039    /// Generates a `Partitioned<u64, u64>` Antichain where all the provided
1040    /// partitions are at the specified offset and the gaps in between are filled with range
1041    /// timestamps at offset zero.
1042    fn partitioned_frontier<I>(items: I) -> Antichain<Partitioned<u64, u64>>
1043    where
1044        I: IntoIterator<Item = (u64, u64)>,
1045    {
1046        let mut frontier = Antichain::new();
1047        let mut prev = 0;
1048        for (pid, offset) in items {
1049            if prev < pid {
1050                frontier.insert(Partitioned::new_range(prev, pid - 1, 0));
1051            }
1052            frontier.insert(Partitioned::new_singleton(pid, offset));
1053            prev = pid + 1
1054        }
1055        frontier.insert(Partitioned::new_range(prev, u64::MAX, 0));
1056        frontier
1057    }
1058
1059    #[mz_ore::test]
1060    fn test_basic_usage() {
1061        let as_of = Antichain::from_elem(IntoTime::minimum());
1062        harness(
1063            as_of,
1064            |worker, mut bindings, (mut data, data_cap), reclocked| {
1065                // Reclock offsets 1 and 3 to timestamp 1000
1066                bindings.update_at(Partitioned::minimum(), 0, Diff::ONE);
1067                bindings.update_at(Partitioned::minimum(), 1000, Diff::MINUS_ONE);
1068                for time in partitioned_frontier([(0, 4)]) {
1069                    bindings.update_at(time, 1000, Diff::ONE);
1070                }
1071                bindings.advance_to(1001);
1072                bindings.flush();
1073                data.activate().session(&data_cap).give_iterator(
1074                    vec![
1075                        (1, Partitioned::new_singleton(0, 1), Diff::ONE),
1076                        (1, Partitioned::new_singleton(0, 1), Diff::ONE),
1077                        (3, Partitioned::new_singleton(0, 3), Diff::ONE),
1078                    ]
1079                    .into_iter(),
1080                );
1081
1082                step(worker);
1083                assert_eq!(
1084                    reclocked.try_recv(),
1085                    Ok(Event::Messages(
1086                        Stamp::from_elem(0u64),
1087                        vec![
1088                            (1, 1000, Diff::ONE),
1089                            (1, 1000, Diff::ONE),
1090                            (3, 1000, Diff::ONE)
1091                        ]
1092                    ))
1093                );
1094                assert_eq!(
1095                    reclocked.try_recv(),
1096                    Ok(Event::Progress(vec![(0, -1), (1000, 1)]))
1097                );
1098
1099                // Reclock more messages for offsets 3 to the same timestamp
1100                data.activate().session(&data_cap).give_iterator(
1101                    vec![
1102                        (3, Partitioned::new_singleton(0, 3), Diff::ONE),
1103                        (3, Partitioned::new_singleton(0, 3), Diff::ONE),
1104                    ]
1105                    .into_iter(),
1106                );
1107                step(worker);
1108                assert_eq!(
1109                    reclocked.try_recv(),
1110                    Ok(Event::Messages(
1111                        Stamp::from_elem(1000u64),
1112                        vec![(3, 1000, Diff::ONE), (3, 1000, Diff::ONE)]
1113                    ))
1114                );
1115
1116                // Drop the capability which should advance the reclocked frontier to 1001.
1117                drop(data_cap);
1118                step(worker);
1119                assert_eq!(reclocked.try_recv(), Ok(Event::Progress(vec![(1000, -1)])));
1120            },
1121        );
1122    }
1123
1124    /// Reclocks updates against many bindings while the source frontier holds the since at the
1125    /// as_of, the way an export does while it snapshots.
1126    #[mz_ore::test]
1127    fn test_reclock_pinned_since() {
1128        harness(
1129            Antichain::from_elem(0),
1130            |worker, mut bindings, (mut data, data_cap), reclocked| {
1131                // The binding at time `t` covers the offsets of partition 0 below `t`.
1132                let mut mint = |times: std::ops::RangeInclusive<u64>| {
1133                    let upper = times.end() + 1;
1134                    for t in times {
1135                        let prev = match t {
1136                            0 => Antichain::new(),
1137                            1 => Antichain::from_elem(Partitioned::minimum()),
1138                            t => partitioned_frontier([(0, t - 1)]),
1139                        };
1140                        let next = match t {
1141                            0 => Antichain::from_elem(Partitioned::minimum()),
1142                            t => partitioned_frontier([(0, t)]),
1143                        };
1144                        for time in prev {
1145                            bindings.update_at(time, t, Diff::MINUS_ONE);
1146                        }
1147                        for time in next {
1148                            bindings.update_at(time, t, Diff::ONE);
1149                        }
1150                    }
1151                    bindings.advance_to(upper);
1152                    bindings.flush();
1153                };
1154                let reclocked_data = || {
1155                    let mut updates: Vec<_> = reclocked
1156                        .try_iter()
1157                        .flat_map(|event| match event {
1158                            Event::Messages(_, updates) => updates,
1159                            Event::Progress(_) => vec![],
1160                        })
1161                        .collect();
1162                    updates.sort();
1163                    updates
1164                };
1165
1166                mint(0..=1000);
1167                // `data_cap` stays at the minimum, which pins the since at the as_of.
1168                let offsets = [0, 1, 63, 64, 500, 998, 999, 1000, 5000];
1169                data.activate().session(&data_cap).give_iterator(
1170                    offsets
1171                        .iter()
1172                        .map(|o| (*o, Partitioned::new_singleton(0, *o), Diff::ONE)),
1173                );
1174                step(worker);
1175                let expected: Vec<_> = offsets[..7]
1176                    .iter()
1177                    .map(|o| (*o, o + 1, Diff::ONE))
1178                    .collect();
1179                assert_eq!(reclocked_data(), expected);
1180
1181                // The updates beyond the last binding wait for the bindings that cover them.
1182                mint(1001..=5001);
1183                step(worker);
1184                assert_eq!(
1185                    reclocked_data(),
1186                    vec![(1000, 1001, Diff::ONE), (5000, 5001, Diff::ONE)]
1187                );
1188            },
1189        );
1190    }
1191
1192    // Test that once the input stream has reached the empty frontier with no pending data we
1193    // eagerly downgrade the output frontier to the empty frontier regardless of the remap stream.
1194    #[mz_ore::test]
1195    fn test_finalized_source() {
1196        let as_of = Antichain::from_elem(IntoTime::minimum());
1197        harness(
1198            as_of,
1199            |worker, mut bindings, (mut data, data_cap), reclocked| {
1200                // The starts by producing data in the source stream and advancing the frontier to
1201                // the empty frontier. The reclock operator buffers the data and holds the
1202                // appropriate capability to reclock the pending data in the future.
1203                data.activate().session(&data_cap).give_iterator(
1204                    vec![
1205                        (1, Partitioned::new_singleton(0, 1), Diff::ONE),
1206                        (2, Partitioned::new_singleton(0, 2), Diff::ONE),
1207                    ]
1208                    .into_iter(),
1209                );
1210                drop(data_cap);
1211                step(worker);
1212
1213                // Reclock offset 0 and 1 to timestamp 1000
1214                bindings.update_at(Partitioned::minimum(), 0, Diff::ONE);
1215                bindings.update_at(Partitioned::minimum(), 1000, Diff::MINUS_ONE);
1216                for time in partitioned_frontier([(0, 2)]) {
1217                    bindings.update_at(time, 1000, Diff::ONE);
1218                }
1219                bindings.advance_to(1001);
1220                bindings.flush();
1221                step(worker);
1222
1223                // At this point the reclock operator is able to release one of the updates and
1224                // downgrade the output capability to timestamp 1001. It can't yet downgrade to the
1225                // empty frontier since the other update is still pending.
1226                assert_eq!(
1227                    reclocked.try_recv(),
1228                    Ok(Event::Messages(
1229                        Stamp::from_elem(0u64),
1230                        vec![(1, 1000, Diff::ONE)]
1231                    ))
1232                );
1233                assert_eq!(
1234                    reclocked.try_recv(),
1235                    Ok(Event::Progress(vec![(0, -1), (1001, 1)]))
1236                );
1237
1238                // Reclock offset 2 to timestamp 2000
1239                for time in partitioned_frontier([(0, 2)]) {
1240                    bindings.update_at(time, 2000, Diff::MINUS_ONE);
1241                }
1242                for time in partitioned_frontier([(0, 3)]) {
1243                    bindings.update_at(time, 2000, Diff::ONE);
1244                }
1245                bindings.advance_to(2001);
1246                bindings.flush();
1247                step(worker);
1248
1249                // Now the reclock operator reclocks the last data item and since the source
1250                // frontier is empty there will be no more work to be done, so the output frontier
1251                // downgrades to the empty frontier even though the frontier of the remap bindings
1252                // is still at [2001].
1253                assert_eq!(
1254                    reclocked.try_recv(),
1255                    Ok(Event::Messages(
1256                        Stamp::from_elem(1001u64),
1257                        vec![(2, 2000, Diff::ONE)]
1258                    ))
1259                );
1260                assert_eq!(reclocked.try_recv(), Ok(Event::Progress(vec![(1001, -1)])));
1261            },
1262        );
1263    }
1264
1265    #[mz_ore::test]
1266    fn test_reclock_frontier() {
1267        let as_of = Antichain::from_elem(IntoTime::minimum());
1268        harness::<_, (), _, _>(
1269            as_of,
1270            |worker, mut bindings, (_data, data_cap), reclocked| {
1271                // Initialize the bindings such that the minimum IntoTime contains the minimum FromTime
1272                // frontier.
1273                bindings.update_at(Partitioned::minimum(), 0, Diff::ONE);
1274                bindings.advance_to(1);
1275                bindings.flush();
1276                step(worker);
1277                assert_eq!(
1278                    reclocked.try_recv(),
1279                    Ok(Event::Progress(vec![(0, -1), (1, 1)]))
1280                );
1281
1282                // Mint a couple of bindings for multiple partitions
1283                bindings.update_at(Partitioned::minimum(), 1000, Diff::MINUS_ONE);
1284                for time in partitioned_frontier([(1, 10)]) {
1285                    bindings.update_at(time.clone(), 1000, Diff::ONE);
1286                    bindings.update_at(time, 2000, Diff::MINUS_ONE);
1287                }
1288                for time in partitioned_frontier([(1, 10), (2, 10)]) {
1289                    bindings.update_at(time, 2000, Diff::ONE);
1290                }
1291                bindings.advance_to(2001);
1292                bindings.flush();
1293
1294                // The initial frontier should now map to the minimum between the two partitions
1295                step(worker);
1296                step(worker);
1297                assert_eq!(
1298                    reclocked.try_recv(),
1299                    Ok(Event::Progress(vec![(1, -1), (1000, 1)]))
1300                );
1301
1302                // Downgrade data frontier such that only one of the partitions is advanced
1303                let mut part1_cap = data_cap.delayed(&Partitioned::new_singleton(1, 9));
1304                let mut part2_cap = data_cap.delayed(&Partitioned::new_singleton(2, 0));
1305                let _rest_cap = data_cap.delayed(&Partitioned::new_range(3, u64::MAX, 0));
1306                drop(data_cap);
1307                step(worker);
1308                assert_eq!(reclocked.try_recv(), Err(TryRecvError::Empty));
1309
1310                // Downgrade the data frontier past the first binding
1311                part1_cap.downgrade(&Partitioned::new_singleton(1, 10));
1312                step(worker);
1313                assert_eq!(
1314                    reclocked.try_recv(),
1315                    Ok(Event::Progress(vec![(1000, -1), (2000, 1)]))
1316                );
1317
1318                // Downgrade the data frontier past the second binding
1319                part2_cap.downgrade(&Partitioned::new_singleton(2, 10));
1320                step(worker);
1321                assert_eq!(
1322                    reclocked.try_recv(),
1323                    Ok(Event::Progress(vec![(2000, -1), (2001, 1)]))
1324                );
1325
1326                // Advance the binding frontier and confirm that we get to the next timestamp
1327                bindings.advance_to(3001);
1328                bindings.flush();
1329                step(worker);
1330                assert_eq!(
1331                    reclocked.try_recv(),
1332                    Ok(Event::Progress(vec![(2001, -1), (3001, 1)]))
1333                );
1334            },
1335        );
1336    }
1337
1338    #[mz_ore::test]
1339    fn test_reclock() {
1340        let as_of = Antichain::from_elem(IntoTime::minimum());
1341        harness(
1342            as_of,
1343            |worker, mut bindings, (mut data, data_cap), reclocked| {
1344                // Initialize the bindings such that the minimum IntoTime contains the minimum FromTime
1345                // frontier.
1346                bindings.update_at(Partitioned::minimum(), 0, Diff::ONE);
1347
1348                // Setup more precise capabilities for the rest of the test
1349                let mut part0_cap = data_cap.delayed(&Partitioned::new_singleton(0, 0));
1350                let rest_cap = data_cap.delayed(&Partitioned::new_range(1, u64::MAX, 0));
1351                drop(data_cap);
1352
1353                // Reclock offsets 1 and 2 to timestamp 1000
1354                data.activate().session(&part0_cap).give_iterator(
1355                    vec![
1356                        (1, Partitioned::new_singleton(0, 1), Diff::ONE),
1357                        (2, Partitioned::new_singleton(0, 2), Diff::ONE),
1358                    ]
1359                    .into_iter(),
1360                );
1361
1362                part0_cap.downgrade(&Partitioned::new_singleton(0, 3));
1363                bindings.update_at(Partitioned::minimum(), 1000, Diff::MINUS_ONE);
1364                bindings.update_at(part0_cap.time().clone(), 1000, Diff::ONE);
1365                bindings.update_at(rest_cap.time().clone(), 1000, Diff::ONE);
1366                bindings.advance_to(1001);
1367                bindings.flush();
1368                step(worker);
1369                assert_eq!(
1370                    reclocked.try_recv(),
1371                    Ok(Event::Messages(
1372                        Stamp::from_elem(0),
1373                        vec![(1, 1000, Diff::ONE), (2, 1000, Diff::ONE)]
1374                    ))
1375                );
1376                assert_eq!(
1377                    reclocked.try_recv(),
1378                    Ok(Event::Progress(vec![(0, -1), (1000, 1)]))
1379                );
1380                assert_eq!(
1381                    reclocked.try_recv(),
1382                    Ok(Event::Progress(vec![(1000, -1), (1001, 1)]))
1383                );
1384
1385                // Reclock offsets 3 and 4 to timestamp 2000
1386                data.activate().session(&part0_cap).give_iterator(
1387                    vec![
1388                        (3, Partitioned::new_singleton(0, 3), Diff::ONE),
1389                        (3, Partitioned::new_singleton(0, 3), Diff::ONE),
1390                        (4, Partitioned::new_singleton(0, 4), Diff::ONE),
1391                    ]
1392                    .into_iter(),
1393                );
1394                bindings.update_at(part0_cap.time().clone(), 2000, Diff::MINUS_ONE);
1395                part0_cap.downgrade(&Partitioned::new_singleton(0, 5));
1396                bindings.update_at(part0_cap.time().clone(), 2000, Diff::ONE);
1397                bindings.advance_to(2001);
1398                bindings.flush();
1399                step(worker);
1400                assert_eq!(
1401                    reclocked.try_recv(),
1402                    Ok(Event::Messages(
1403                        Stamp::from_elem(1001),
1404                        vec![
1405                            (3, 2000, Diff::ONE),
1406                            (3, 2000, Diff::ONE),
1407                            (4, 2000, Diff::ONE)
1408                        ]
1409                    ))
1410                );
1411                assert_eq!(
1412                    reclocked.try_recv(),
1413                    Ok(Event::Progress(vec![(1001, -1), (2000, 1)]))
1414                );
1415                assert_eq!(
1416                    reclocked.try_recv(),
1417                    Ok(Event::Progress(vec![(2000, -1), (2001, 1)]))
1418                );
1419            },
1420        );
1421    }
1422
1423    #[mz_ore::test]
1424    fn test_reclock_gh16318() {
1425        let as_of = Antichain::from_elem(IntoTime::minimum());
1426        harness(
1427            as_of,
1428            |worker, mut bindings, (mut data, data_cap), reclocked| {
1429                // Initialize the bindings such that the minimum IntoTime contains the minimum FromTime
1430                // frontier.
1431                bindings.update_at(Partitioned::minimum(), 0, Diff::ONE);
1432                // First mint bindings for 0 at timestamp 1000
1433                bindings.update_at(Partitioned::minimum(), 1000, Diff::MINUS_ONE);
1434                for time in partitioned_frontier([(0, 50)]) {
1435                    bindings.update_at(time, 1000, Diff::ONE);
1436                }
1437                // Then only for 1 at timestamp 2000
1438                for time in partitioned_frontier([(0, 50)]) {
1439                    bindings.update_at(time, 2000, Diff::MINUS_ONE);
1440                }
1441                for time in partitioned_frontier([(0, 50), (1, 50)]) {
1442                    bindings.update_at(time, 2000, Diff::ONE);
1443                }
1444                // Then again only for 0 at timestamp 3000
1445                for time in partitioned_frontier([(0, 50), (1, 50)]) {
1446                    bindings.update_at(time, 3000, Diff::MINUS_ONE);
1447                }
1448                for time in partitioned_frontier([(0, 100), (1, 50)]) {
1449                    bindings.update_at(time, 3000, Diff::ONE);
1450                }
1451                bindings.advance_to(3001);
1452                bindings.flush();
1453
1454                // Reclockng (0, 50) must ignore the updates on the FromTime frontier that happened at
1455                // timestamp 2000 since those are completely unrelated
1456                data.activate().session(&data_cap).give((
1457                    50,
1458                    Partitioned::new_singleton(0, 50),
1459                    Diff::ONE,
1460                ));
1461                drop(data_cap);
1462                step(worker);
1463                assert_eq!(
1464                    reclocked.try_recv(),
1465                    Ok(Event::Messages(
1466                        Stamp::from_elem(0),
1467                        vec![(50, 3000, Diff::ONE),]
1468                    ))
1469                );
1470                assert_eq!(
1471                    reclocked.try_recv(),
1472                    Ok(Event::Progress(vec![(0, -1), (1000, 1)]))
1473                );
1474                assert_eq!(reclocked.try_recv(), Ok(Event::Progress(vec![(1000, -1)])));
1475            },
1476        );
1477    }
1478
1479    /// Test that compact(reclock(remap, source)) == reclock(compact(remap), source)
1480    #[mz_ore::test]
1481    fn test_compaction() {
1482        let mut remap = vec![];
1483        remap.push((Partitioned::minimum(), 0, Diff::ONE));
1484        // Reclock offsets 1 and 2 to timestamp 1000
1485        remap.push((Partitioned::minimum(), 1000, Diff::MINUS_ONE));
1486        for time in partitioned_frontier([(0, 3)]) {
1487            remap.push((time, 1000, Diff::ONE));
1488        }
1489        // Reclock offsets 3 and 4 to timestamp 2000
1490        for time in partitioned_frontier([(0, 3)]) {
1491            remap.push((time, 2000, Diff::MINUS_ONE));
1492        }
1493        for time in partitioned_frontier([(0, 5)]) {
1494            remap.push((time, 2000, Diff::ONE));
1495        }
1496
1497        let source_updates = vec![
1498            (1, Partitioned::new_singleton(0, 1), Diff::ONE),
1499            (2, Partitioned::new_singleton(0, 2), Diff::ONE),
1500            (3, Partitioned::new_singleton(0, 3), Diff::ONE),
1501            (4, Partitioned::new_singleton(0, 4), Diff::ONE),
1502        ];
1503
1504        let since = Antichain::from_elem(1500);
1505
1506        // Compute reclock(remap, source)
1507        let as_of = Antichain::from_elem(IntoTime::minimum());
1508        let remap1 = remap.clone();
1509        let source_updates1 = source_updates.clone();
1510        let reclock_remap = harness(
1511            as_of,
1512            move |worker, mut bindings, (mut data, data_cap), reclocked| {
1513                for (from_ts, into_ts, diff) in remap1 {
1514                    bindings.update_at(from_ts, into_ts, diff);
1515                }
1516                bindings.close();
1517                data.activate()
1518                    .session(&data_cap)
1519                    .give_iterator(source_updates1.iter().cloned());
1520                drop(data_cap);
1521                step(worker);
1522                reclocked.extract()
1523            },
1524        );
1525        // Compute compact(reclock(remap, source))
1526        let mut compact_reclock_remap = reclock_remap;
1527        for (t, updates) in compact_reclock_remap.iter_mut() {
1528            t.advance_by(since.borrow());
1529            for (_, t, _) in updates.iter_mut() {
1530                t.advance_by(since.borrow());
1531            }
1532        }
1533
1534        // Compute compact(remap)
1535        let mut compact_remap = remap;
1536        for (_, t, _) in compact_remap.iter_mut() {
1537            t.advance_by(since.borrow());
1538        }
1539        consolidation::consolidate_updates(&mut compact_remap);
1540        // Compute reclock(compact(remap), source)
1541        let reclock_compact_remap = harness(
1542            since,
1543            move |worker, mut bindings, (mut data, data_cap), reclocked| {
1544                for (from_ts, into_ts, diff) in compact_remap {
1545                    bindings.update_at(from_ts, into_ts, diff);
1546                }
1547                bindings.close();
1548                data.activate()
1549                    .session(&data_cap)
1550                    .give_iterator(source_updates.iter().cloned());
1551                drop(data_cap);
1552                step(worker);
1553                reclocked.extract()
1554            },
1555        );
1556
1557        let expected = vec![(
1558            1500,
1559            vec![
1560                (1, 1500, Diff::ONE),
1561                (2, 1500, Diff::ONE),
1562                (3, 2000, Diff::ONE),
1563                (4, 2000, Diff::ONE),
1564            ],
1565        )];
1566        assert_eq!(expected, reclock_compact_remap);
1567        assert_eq!(expected, compact_reclock_remap);
1568    }
1569
1570    /// Returns the updates of a remap collection whose binding at time `i` is the `i`th of
1571    /// `frontiers`.
1572    fn remap_updates(
1573        frontiers: impl IntoIterator<Item = Antichain<FromTime>>,
1574    ) -> Vec<(FromTime, IntoTime, i64)> {
1575        let mut updates = vec![];
1576        let mut prev = Antichain::new();
1577        for (time, frontier) in frontiers.into_iter().enumerate() {
1578            let time = u64::cast_from(time);
1579            let mut batch: Vec<_> = prev.into_iter().map(|t| (t, time, -1)).collect();
1580            batch.extend(frontier.iter().cloned().map(|t| (t, time, 1)));
1581            consolidation::consolidate_updates(&mut batch);
1582            updates.extend(batch);
1583            prev = frontier;
1584        }
1585        updates
1586    }
1587
1588    /// Returns the updates of a remap collection with partitions `0..parts`, all at offset 0 at
1589    /// time 0. Each time from 1 to `times` advances partition `time % parts` by one.
1590    fn round_robin_remap(parts: usize, times: u64) -> Vec<(FromTime, IntoTime, i64)> {
1591        let mut offsets = vec![0; parts];
1592        remap_updates((0..=times).map(|time| {
1593            if time > 0 {
1594                offsets[usize::cast_from(time) % parts] += 1;
1595            }
1596            partitioned_frontier(
1597                offsets
1598                    .iter()
1599                    .enumerate()
1600                    .map(|(pid, offset)| (u64::cast_from(pid), *offset)),
1601            )
1602        }))
1603    }
1604
1605    /// The pids that [`growing_remap`] draws from are below this.
1606    const GROWING_PIDS: usize = 301;
1607
1608    /// Returns the updates of a remap collection that holds partition 0 at time 0 and gains a
1609    /// partition at every fifth time up to `times`. The new pids are scattered, which makes each
1610    /// one split a range of the binding. Every other time advances one partition by one.
1611    fn growing_remap(times: u64) -> Vec<(FromTime, IntoTime, i64)> {
1612        let mut offsets = BTreeMap::from([(0, 0)]);
1613        remap_updates((0..=times).map(|time| {
1614            if time > 0 && time % 5 == 0 {
1615                // 101 is prime, which keeps the pids distinct for the first 100 additions.
1616                assert!(time / 5 < 101, "too many partitions");
1617                offsets.insert(time / 5 * 37 % 101 * 3, 0);
1618            } else if time > 0 {
1619                let index = usize::cast_from(time) % offsets.len();
1620                let offset = offsets.values_mut().nth(index).expect("index is in range");
1621                *offset += 1;
1622            }
1623            partitioned_frontier(offsets.iter().map(|(pid, offset)| (*pid, *offset)))
1624        }))
1625    }
1626
1627    #[mz_ore::test]
1628    #[cfg_attr(miri, ignore)] // too slow
1629    fn remap_trace_seek_matches_scan() {
1630        // With one partition each time has as many updates as its bindings hold elements, so
1631        // every binding is a keyframe. 70 partitions leave updates between keyframes.
1632        for (parts, times, between) in [(1, 1000, false), (70, 350, true)] {
1633            let updates = round_robin_remap(parts, times);
1634            let mut trace = RemapTrace::new(Antichain::from_elem(0));
1635            push_all(&mut trace, &updates);
1636            assert!(trace.keyframes.len() > 2, "{parts} partitions");
1637            assert_eq!(!trace.updates.is_empty(), between, "{parts} partitions");
1638
1639            for since in [0, times / 3, times / 2] {
1640                trace.advance_since(Antichain::from_elem(since));
1641                assert_seeks_match_scan(&trace, &updates, parts, since);
1642            }
1643        }
1644    }
1645
1646    /// Compaction moves the since past the last binding when the remap frontier advances without
1647    /// new bindings. The bindings pushed after that must build on the binding at the since.
1648    #[mz_ore::test]
1649    #[cfg_attr(miri, ignore)] // too slow
1650    fn remap_trace_push_after_compaction() {
1651        // 70 partitions leave updates after the last keyframe for compaction to apply to it.
1652        for parts in [1, 70] {
1653            let mut updates = round_robin_remap(parts, 400);
1654            // Leave the times from 201 to 219 without bindings.
1655            for (_, into, _) in &mut updates {
1656                if *into > 200 {
1657                    *into += 19;
1658                }
1659            }
1660            let split = updates.partition_point(|(_, into, _)| *into <= 200);
1661            let mut trace = RemapTrace::new(Antichain::from_elem(0));
1662            push_all(&mut trace, &updates[..split]);
1663            trace.advance_since(Antichain::from_elem(210));
1664            push_all(&mut trace, &updates[split..]);
1665            assert_seeks_match_scan(&trace, &updates, parts, 210);
1666        }
1667    }
1668
1669    #[mz_ore::test]
1670    #[cfg_attr(miri, ignore)] // too slow
1671    fn remap_trace_seek_matches_scan_with_growing_partitions() {
1672        let updates = growing_remap(350);
1673        let mut trace = RemapTrace::new(Antichain::from_elem(0));
1674        push_all(&mut trace, &updates);
1675        assert!(trace.keyframes.len() > 2);
1676        assert!(!trace.updates.is_empty());
1677
1678        for since in [0, 120, 175] {
1679            trace.advance_since(Antichain::from_elem(since));
1680            assert_seeks_match_scan(&trace, &updates, GROWING_PIDS, since);
1681        }
1682    }
1683
1684    /// Pushes `updates`, which must be in time order, into `trace` one time at a time.
1685    fn push_all(trace: &mut RemapTrace<FromTime, IntoTime>, updates: &[(FromTime, IntoTime, i64)]) {
1686        for tick in updates.chunk_by(|(_, into1, _), (_, into2, _)| into1 == into2) {
1687            let (_, into, _) = tick[0];
1688            trace.push(
1689                into,
1690                tick.iter().map(|(from, _, diff)| (from.clone(), *diff)),
1691            );
1692        }
1693    }
1694
1695    /// Asserts that seeking `trace`, whose since is `since`, finds the same binding for every
1696    /// offset of partitions `0..parts` as scanning the bindings that `updates` accumulate to.
1697    fn assert_seeks_match_scan(
1698        trace: &RemapTrace<FromTime, IntoTime>,
1699        updates: &[(FromTime, IntoTime, i64)],
1700        parts: usize,
1701        since: IntoTime,
1702    ) {
1703        // The binding at every time, accumulated from the front.
1704        let mut accum = MutableAntichain::new();
1705        let mut all_bindings: Vec<(IntoTime, Antichain<FromTime>)> = vec![];
1706        for (from, into, diff) in updates {
1707            accum.update_iter([(from.clone(), *diff)]);
1708            match all_bindings.last_mut() {
1709                Some((time, binding)) if time == into => *binding = accum.frontier().to_owned(),
1710                _ => all_bindings.push((*into, accum.frontier().to_owned())),
1711            }
1712        }
1713        // The since takes the binding of the last time at or before it.
1714        let first = all_bindings.partition_point(|(time, _)| *time <= since) - 1;
1715        let mut bindings = all_bindings[first..].to_vec();
1716        bindings[0].0 = since;
1717
1718        for pid in 0..u64::cast_from(parts) {
1719            // One cursor serves the queries of a partition. It only moves forward, so it skips the
1720            // queries that map to the binding it is already at.
1721            let mut cursor = trace.cursor();
1722            let mut cursor_time = None;
1723            for offset in 0.. {
1724                let query = Partitioned::new_singleton(pid, offset);
1725                let expected = bindings
1726                    .iter()
1727                    .find(|(_, binding)| !binding.less_equal(&query))
1728                    .map(|(time, _)| *time);
1729                let from_fresh = trace
1730                    .cursor()
1731                    .seek(|binding| !binding.less_equal(&query))
1732                    .map(|(time, _)| *time);
1733                assert_eq!(
1734                    from_fresh, expected,
1735                    "fresh cursor, since {since}, {query:?}"
1736                );
1737                if expected != cursor_time {
1738                    cursor_time = cursor
1739                        .seek(|binding| !binding.less_equal(&query))
1740                        .map(|(time, _)| *time);
1741                    assert_eq!(
1742                        cursor_time, expected,
1743                        "moved cursor, since {since}, {query:?}"
1744                    );
1745                }
1746                if expected.is_none() {
1747                    break;
1748                }
1749            }
1750        }
1751    }
1752
1753    #[mz_ore::test]
1754    fn test_chainbatch_merge() {
1755        let a = ChainBatch::from_iter([('a', 0, 1)]);
1756        let b = ChainBatch::from_iter([('a', 0, -1), ('a', 1, 1)]);
1757        assert_eq!(a.merge_with(b), ChainBatch::from_iter([('a', 1, 1)]));
1758    }
1759
1760    #[mz_ore::test]
1761    #[cfg_attr(miri, ignore)] // too slow
1762    fn test_binding_consolidation() {
1763        use std::sync::atomic::Ordering;
1764
1765        #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
1766        struct Time(u64);
1767
1768        // A counter of the number of active Time instances
1769        static INSTANCES: AtomicUsize = AtomicUsize::new(0);
1770
1771        impl Time {
1772            fn new(time: u64) -> Self {
1773                INSTANCES.fetch_add(1, Ordering::Relaxed);
1774                Self(time)
1775            }
1776        }
1777
1778        impl Clone for Time {
1779            fn clone(&self) -> Self {
1780                INSTANCES.fetch_add(1, Ordering::Relaxed);
1781                Self(self.0)
1782            }
1783        }
1784
1785        impl Drop for Time {
1786            fn drop(&mut self) {
1787                INSTANCES.fetch_sub(1, Ordering::Relaxed);
1788            }
1789        }
1790
1791        impl Timestamp for Time {
1792            type Summary = ();
1793
1794            fn minimum() -> Self {
1795                Time::new(0)
1796            }
1797        }
1798
1799        impl PathSummary<Time> for () {
1800            fn results_in(&self, src: &Time) -> Option<Time> {
1801                Some(src.clone())
1802            }
1803
1804            fn followed_by(&self, _other: &()) -> Option<Self> {
1805                Some(())
1806            }
1807        }
1808
1809        impl Refines<()> for Time {
1810            fn to_inner(_: ()) -> Self {
1811                Self::minimum()
1812            }
1813            fn to_outer(self) -> () {}
1814            fn summarize(_path: ()) {}
1815        }
1816
1817        impl PartialOrder for Time {
1818            fn less_equal(&self, other: &Self) -> bool {
1819                self.0.less_equal(&other.0)
1820            }
1821        }
1822
1823        let as_of = 1000;
1824
1825        // Test that supplying a single big batch of unconsolidated bindings gets
1826        // consolidated after a single worker step.
1827        harness::<Time, u64, _, _>(
1828            Antichain::from_elem(as_of),
1829            move |worker, mut bindings, _, _| {
1830                step(worker);
1831                let instances_before = INSTANCES.load(Ordering::Relaxed);
1832                for ts in 0..as_of {
1833                    if ts > 0 {
1834                        bindings.update_at(Time::new(ts - 1), ts, Diff::MINUS_ONE);
1835                    }
1836                    bindings.update_at(Time::new(ts), ts, Diff::ONE);
1837                }
1838                bindings.advance_to(as_of);
1839                bindings.flush();
1840                step(worker);
1841                let instances_after = INSTANCES.load(Ordering::Relaxed);
1842                // The extra instances live in a ChangeBatch which considers compaction when more
1843                // than 32 elements are inside.
1844                assert!(instances_after - instances_before < 32);
1845            },
1846        );
1847
1848        // Test that a slow feed of uncompacted bindings over multiple steps never leads to an
1849        // excessive number of bindings held in memory.
1850        harness::<Time, u64, _, _>(
1851            Antichain::from_elem(as_of),
1852            move |worker, mut bindings, _, _| {
1853                step(worker);
1854                let instances_before = INSTANCES.load(Ordering::Relaxed);
1855                for ts in 0..as_of {
1856                    if ts > 0 {
1857                        bindings.update_at(Time::new(ts - 1), ts, Diff::MINUS_ONE);
1858                    }
1859                    bindings.update_at(Time::new(ts), ts, Diff::ONE);
1860                    bindings.advance_to(ts + 1);
1861                    bindings.flush();
1862                    step(worker);
1863                    let instances_now = INSTANCES.load(Ordering::Relaxed);
1864                    // The extra instances live in a ChangeBatch which considers compaction when
1865                    // more than 32 elements are inside.
1866                    assert!(instances_now - instances_before < 32);
1867                }
1868            },
1869        );
1870    }
1871
1872    #[cfg(feature = "count-allocations")]
1873    #[mz_ore::test]
1874    #[cfg_attr(miri, ignore)] // too slow
1875    fn test_shrinking() {
1876        let as_of = 1000_u64;
1877
1878        // This workflow accumulates updates in remap_trace, advances the source frontier,
1879        // and validates that memory was reclaimed.  To avoid errant test failures due to
1880        // optimizations, this only validates that memory is reclaimed, not how much.
1881        harness::<FromTime, u64, _, _>(
1882            Antichain::from_elem(0),
1883            move |worker, mut bindings, (_data, mut data_cap), _| {
1884                let info1 = allocation_counter::measure(|| {
1885                    step(worker);
1886                    for ts in 0..as_of {
1887                        if ts > 0 {
1888                            bindings.update_at(
1889                                Partitioned::new_singleton(0, ts - 1),
1890                                ts,
1891                                Diff::MINUS_ONE,
1892                            );
1893                        }
1894                        bindings.update_at(Partitioned::new_singleton(0, ts), ts, Diff::ONE);
1895                        bindings.advance_to(ts + 1);
1896                        bindings.flush();
1897                        step(worker);
1898                    }
1899                });
1900                println!("info = {info1:?}");
1901
1902                let info2 = allocation_counter::measure(|| {
1903                    data_cap.downgrade(&Partitioned::new_singleton(0, as_of));
1904                    step(worker);
1905                });
1906                println!("info = {info2:?}");
1907                assert!(info2.bytes_current < 0);
1908            },
1909        );
1910    }
1911
1912    #[cfg(feature = "count-allocations")]
1913    #[mz_ore::test]
1914    #[cfg_attr(miri, ignore)] // too slow
1915    fn test_replay_releases_buffers() {
1916        let replayed = 10_000_u64;
1917
1918        // The source frontier is beyond every replayed binding, so the trace keeps none of them
1919        // and what stays allocated after the replay is buffer capacity.
1920        harness::<FromTime, u64, _, _>(
1921            Antichain::from_elem(0),
1922            move |worker, mut bindings, (_data, mut data_cap), reclocked| {
1923                data_cap.downgrade(&Partitioned::new_singleton(0, replayed));
1924                step(worker);
1925                let info = allocation_counter::measure(|| {
1926                    for ts in 0..replayed {
1927                        if ts > 0 {
1928                            bindings.update_at(
1929                                Partitioned::new_singleton(0, ts - 1),
1930                                ts,
1931                                Diff::MINUS_ONE,
1932                            );
1933                        }
1934                        bindings.update_at(Partitioned::new_singleton(0, ts), ts, Diff::ONE);
1935                    }
1936                    bindings.advance_to(replayed);
1937                    bindings.flush();
1938                    step(worker);
1939                    reclocked.try_iter().for_each(drop);
1940                });
1941                assert!(
1942                    info.bytes_current < i64::try_from(info.bytes_max / 10).expect("fits"),
1943                    "replay buffers kept their capacity: {info:?}"
1944                );
1945            },
1946        );
1947    }
1948}