differential_dataflow/trace/mod.rs
1//! Traits and datastructures representing a collection trace.
2//!
3//! A collection trace is a set of updates of the form `(key, val, time, diff)`, which determine the contents
4//! of a collection at given times by accumulating updates whose time field is less or equal to the target field.
5//!
6//! The `Trace` trait describes those types and methods that a data structure must implement to be viewed as a
7//! collection trace. This trait allows operator implementations to be generic with respect to the type of trace,
8//! and allows various data structures to be interpretable as multiple different types of trace.
9
10pub mod cursor;
11pub mod description;
12pub mod implementations;
13pub mod wrappers;
14
15use timely::progress::{Antichain, frontier::AntichainRef};
16use timely::progress::Timestamp;
17
18use crate::logging::Logger;
19use crate::difference::Semigroup;
20use crate::IntoOwned;
21use crate::lattice::Lattice;
22pub use self::cursor::Cursor;
23pub use self::description::Description;
24
25/// A type used to express how much effort a trace should exert even in the absence of updates.
26pub type ExertionLogic = std::sync::Arc<dyn for<'a> Fn(&'a [(usize, usize, usize)])->Option<usize>+Send+Sync>;
27
28// The traces and batch and cursors want the flexibility to appear as if they manage certain types of keys and
29// values and such, while perhaps using other representations, I'm thinking mostly of wrappers around the keys
30// and vals that change the `Ord` implementation, or stash hash codes, or the like.
31//
32// This complicates what requirements we make so that the trace is still usable by someone who knows only about
33// the base key and value types. For example, the complex types should likely dereference to the simpler types,
34// so that the user can make sense of the result as if they were given references to the simpler types. At the
35// same time, the collection should be formable from base types (perhaps we need an `Into` or `From` constraint)
36// and we should, somehow, be able to take a reference to the simple types to compare against the more complex
37// types. This second one is also like an `Into` or `From` constraint, except that we start with a reference and
38// really don't need anything more complex than a reference, but we can't form an owned copy of the complex type
39// without cloning it.
40//
41// We could just start by cloning things. Worry about wrapping references later on.
42
43/// A trace whose contents may be read.
44///
45/// This is a restricted interface to the more general `Trace` trait, which extends this trait with further methods
46/// to update the contents of the trace. These methods are used to examine the contents, and to update the reader's
47/// capabilities (which may release restrictions on the mutations to the underlying trace and cause work to happen).
48pub trait TraceReader {
49
50 /// Key by which updates are indexed.
51 type Key<'a>: Copy + Clone + Ord;
52 /// Values associated with keys.
53 type Val<'a>: Copy + Clone;
54 /// Timestamps associated with updates
55 type Time: Timestamp + Lattice + Ord + Clone;
56 /// Borrowed form of timestamp.
57 type TimeGat<'a>: Copy + IntoOwned<'a, Owned = Self::Time>;
58 /// Owned form of update difference.
59 type Diff: Semigroup + 'static;
60 /// Borrowed form of update difference.
61 type DiffGat<'a> : Copy + IntoOwned<'a, Owned = Self::Diff>;
62
63 /// The type of an immutable collection of updates.
64 type Batch: for<'a> BatchReader<Key<'a> = Self::Key<'a>, Val<'a> = Self::Val<'a>, Time = Self::Time, TimeGat<'a> = Self::TimeGat<'a>, Diff = Self::Diff, DiffGat<'a> = Self::DiffGat<'a>>+Clone+'static;
65
66 /// Storage type for `Self::Cursor`. Likely related to `Self::Batch`.
67 type Storage;
68
69 /// The type used to enumerate the collections contents.
70 type Cursor: for<'a> Cursor<Storage=Self::Storage, Key<'a> = Self::Key<'a>, Val<'a> = Self::Val<'a>, Time = Self::Time, TimeGat<'a> = Self::TimeGat<'a>, Diff = Self::Diff, DiffGat<'a> = Self::DiffGat<'a>>;
71
72 /// Provides a cursor over updates contained in the trace.
73 fn cursor(&mut self) -> (Self::Cursor, Self::Storage) {
74 if let Some(cursor) = self.cursor_through(Antichain::new().borrow()) {
75 cursor
76 }
77 else {
78 panic!("unable to acquire complete cursor for trace; is it closed?");
79 }
80 }
81
82 /// Acquires a cursor to the restriction of the collection's contents to updates at times not greater or
83 /// equal to an element of `upper`.
84 ///
85 /// This method is expected to work if called with an `upper` that (i) was an observed bound in batches from
86 /// the trace, and (ii) the trace has not been advanced beyond `upper`. Practically, the implementation should
87 /// be expected to look for a "clean cut" using `upper`, and if it finds such a cut can return a cursor. This
88 /// should allow `upper` such as `&[]` as used by `self.cursor()`, though it is difficult to imagine other uses.
89 fn cursor_through(&mut self, upper: AntichainRef<Self::Time>) -> Option<(Self::Cursor, Self::Storage)>;
90
91 /// Advances the frontier that constrains logical compaction.
92 ///
93 /// Logical compaction is the ability of the trace to change the times of the updates it contains.
94 /// Update times may be changed as long as their comparison to all query times beyond the logical compaction
95 /// frontier remains unchanged. Practically, this means that groups of timestamps not beyond the frontier can
96 /// be coalesced into fewer representative times.
97 ///
98 /// Logical compaction is important, as it allows the trace to forget historical distinctions between update
99 /// times, and maintain a compact memory footprint over an unbounded update history.
100 ///
101 /// By advancing the logical compaction frontier, the caller unblocks merging of otherwise equivalent updates,
102 /// but loses the ability to observe historical detail that is not beyond `frontier`.
103 ///
104 /// It is an error to call this method with a frontier not equal to or beyond the most recent arguments to
105 /// this method, or the initial value of `get_logical_compaction()` if this method has not yet been called.
106 fn set_logical_compaction(&mut self, frontier: AntichainRef<Self::Time>);
107
108 /// Reports the logical compaction frontier.
109 ///
110 /// All update times beyond this frontier will be presented with their original times, and all update times
111 /// not beyond this frontier will present as a time that compares identically with all query times beyond
112 /// this frontier. Practically, update times not beyond this frontier should not be taken to be accurate as
113 /// presented, and should be used carefully, only in accumulation to times that are beyond the frontier.
114 fn get_logical_compaction(&mut self) -> AntichainRef<Self::Time>;
115
116 /// Advances the frontier that constrains physical compaction.
117 ///
118 /// Physical compaction is the ability of the trace to merge the batches of updates it maintains. Physical
119 /// compaction does not change the updates or their timestamps, although it is also the moment at which
120 /// logical compaction is most likely to happen.
121 ///
122 /// Physical compaction allows the trace to maintain a logarithmic number of batches of updates, which is
123 /// what allows the trace to provide efficient random access by keys and values.
124 ///
125 /// By advancing the physical compaction frontier, the caller unblocks the merging of batches of updates,
126 /// but loses the ability to create a cursor through any frontier not beyond `frontier`.
127 ///
128 /// It is an error to call this method with a frontier not equal to or beyond the most recent arguments to
129 /// this method, or the initial value of `get_physical_compaction()` if this method has not yet been called.
130 fn set_physical_compaction(&mut self, frontier: AntichainRef<Self::Time>);
131
132 /// Reports the physical compaction frontier.
133 ///
134 /// All batches containing updates beyond this frontier will not be merged with other batches. This allows
135 /// the caller to create a cursor through any frontier beyond the physical compaction frontier, with the
136 /// `cursor_through()` method. This functionality is primarily of interest to the `join` operator, and any
137 /// other operators who need to take notice of the physical structure of update batches.
138 fn get_physical_compaction(&mut self) -> AntichainRef<Self::Time>;
139
140 /// Maps logic across the non-empty sequence of batches in the trace.
141 ///
142 /// This is currently used only to extract historical data to prime late-starting operators who want to reproduce
143 /// the stream of batches moving past the trace. It could also be a fine basis for a default implementation of the
144 /// cursor methods, as they (by default) just move through batches accumulating cursors into a cursor list.
145 fn map_batches<F: FnMut(&Self::Batch)>(&self, f: F);
146
147 /// Reads the upper frontier of committed times.
148 ///
149 ///
150 #[inline]
151 fn read_upper(&mut self, target: &mut Antichain<Self::Time>) {
152 target.clear();
153 target.insert(<Self::Time as timely::progress::Timestamp>::minimum());
154 self.map_batches(|batch| {
155 target.clone_from(batch.upper());
156 });
157 }
158
159 /// Advances `upper` by any empty batches.
160 ///
161 /// An empty batch whose `batch.lower` bound equals the current
162 /// contents of `upper` will advance `upper` to `batch.upper`.
163 /// Taken across all batches, this should advance `upper` across
164 /// empty batch regions.
165 fn advance_upper(&mut self, upper: &mut Antichain<Self::Time>) {
166 self.map_batches(|batch| {
167 if batch.is_empty() && batch.lower() == upper {
168 upper.clone_from(batch.upper());
169 }
170 });
171 }
172
173}
174
175/// An append-only collection of `(key, val, time, diff)` tuples.
176///
177/// The trace must pretend to look like a collection of `(Key, Val, Time, isize)` tuples, but is permitted
178/// to introduce new types `KeyRef`, `ValRef`, and `TimeRef` which can be dereference to the types above.
179///
180/// The trace must be constructable from, and navigable by the `Key`, `Val`, `Time` types, but does not need
181/// to return them.
182pub trait Trace : TraceReader
183where <Self as TraceReader>::Batch: Batch {
184
185 /// Allocates a new empty trace.
186 fn new(
187 info: ::timely::dataflow::operators::generic::OperatorInfo,
188 logging: Option<crate::logging::Logger>,
189 activator: Option<timely::scheduling::activate::Activator>,
190 ) -> Self;
191
192 /// Exert merge effort, even without updates.
193 fn exert(&mut self);
194
195 /// Sets the logic for exertion in the absence of updates.
196 ///
197 /// The function receives an iterator over batch levels, from large to small, as triples `(level, count, length)`,
198 /// indicating the level, the number of batches, and their total length in updates. It should return a number of
199 /// updates to perform, or `None` if no work is required.
200 fn set_exert_logic(&mut self, logic: ExertionLogic);
201
202 /// Introduces a batch of updates to the trace.
203 ///
204 /// Batches describe the time intervals they contain, and they should be added to the trace in contiguous
205 /// intervals. If a batch arrives with a lower bound that does not equal the upper bound of the most recent
206 /// addition, the trace will add an empty batch. It is an error to then try to populate that region of time.
207 ///
208 /// This restriction could be relaxed, especially if we discover ways in which batch interval order could
209 /// commute. For now, the trace should complain, to the extent that it cares about contiguous intervals.
210 fn insert(&mut self, batch: Self::Batch);
211
212 /// Introduces an empty batch concluding the trace.
213 ///
214 /// This method should be logically equivalent to introducing an empty batch whose lower frontier equals
215 /// the upper frontier of the most recently introduced batch, and whose upper frontier is empty.
216 fn close(&mut self);
217}
218
219/// A batch of updates whose contents may be read.
220///
221/// This is a restricted interface to batches of updates, which support the reading of the batch's contents,
222/// but do not expose ways to construct the batches. This trait is appropriate for views of the batch, and is
223/// especially useful for views derived from other sources in ways that prevent the construction of batches
224/// from the type of data in the view (for example, filtered views, or views with extended time coordinates).
225pub trait BatchReader
226where
227 Self: ::std::marker::Sized,
228{
229 /// Key by which updates are indexed.
230 type Key<'a>: Copy + Clone + Ord;
231 /// Values associated with keys.
232 type Val<'a>: Copy + Clone;
233 /// Timestamps associated with updates
234 type Time: Timestamp + Lattice + Ord + Clone;
235 /// Borrowed form of timestamp.
236 type TimeGat<'a>: Copy + IntoOwned<'a, Owned = Self::Time>;
237 /// Owned form of update difference.
238 type Diff: Semigroup + 'static;
239 /// Borrowed form of update difference.
240 type DiffGat<'a> : Copy + IntoOwned<'a, Owned = Self::Diff>;
241
242 /// The type used to enumerate the batch's contents.
243 type Cursor: for<'a> Cursor<Storage=Self, Key<'a> = Self::Key<'a>, Val<'a> = Self::Val<'a>, Time = Self::Time, TimeGat<'a> = Self::TimeGat<'a>, Diff = Self::Diff, DiffGat<'a> = Self::DiffGat<'a>>;
244 /// Acquires a cursor to the batch's contents.
245 fn cursor(&self) -> Self::Cursor;
246 /// The number of updates in the batch.
247 fn len(&self) -> usize;
248 /// True if the batch is empty.
249 fn is_empty(&self) -> bool { self.len() == 0 }
250 /// Describes the times of the updates in the batch.
251 fn description(&self) -> &Description<Self::Time>;
252
253 /// All times in the batch are greater or equal to an element of `lower`.
254 fn lower(&self) -> &Antichain<Self::Time> { self.description().lower() }
255 /// All times in the batch are not greater or equal to any element of `upper`.
256 fn upper(&self) -> &Antichain<Self::Time> { self.description().upper() }
257}
258
259/// An immutable collection of updates.
260pub trait Batch : BatchReader where Self: ::std::marker::Sized {
261 /// A type used to progressively merge batches.
262 type Merger: Merger<Self>;
263
264 /// Initiates the merging of consecutive batches.
265 ///
266 /// The result of this method can be exercised to eventually produce the same result
267 /// that a call to `self.merge(other)` would produce, but it can be done in a measured
268 /// fashion. This can help to avoid latency spikes where a large merge needs to happen.
269 fn begin_merge(&self, other: &Self, compaction_frontier: AntichainRef<Self::Time>) -> Self::Merger {
270 Self::Merger::new(self, other, compaction_frontier)
271 }
272
273 /// Produce an empty batch over the indicated interval.
274 fn empty(lower: Antichain<Self::Time>, upper: Antichain<Self::Time>) -> Self;
275}
276
277/// Functionality for collecting and batching updates.
278pub trait Batcher {
279 /// Type pushed into the batcher.
280 type Input;
281 /// Type produced by the batcher.
282 type Output;
283 /// Times at which batches are formed.
284 type Time: Timestamp;
285 /// Allocates a new empty batcher.
286 fn new(logger: Option<Logger>, operator_id: usize) -> Self;
287 /// Adds an unordered container of elements to the batcher.
288 fn push_container(&mut self, batch: &mut Self::Input);
289 /// Returns all updates not greater or equal to an element of `upper`.
290 fn seal<B: Builder<Input=Self::Output, Time=Self::Time>>(&mut self, upper: Antichain<Self::Time>) -> B::Output;
291 /// Returns the lower envelope of contained update times.
292 fn frontier(&mut self) -> timely::progress::frontier::AntichainRef<Self::Time>;
293}
294
295/// Functionality for building batches from ordered update sequences.
296pub trait Builder: Sized {
297 /// Input item type.
298 type Input;
299 /// Timestamp type.
300 type Time: Timestamp;
301 /// Output batch type.
302 type Output;
303
304 /// Allocates an empty builder.
305 ///
306 /// Ideally we deprecate this and insist all non-trivial building happens via `with_capacity()`.
307 // #[deprecated]
308 fn new() -> Self { Self::with_capacity(0, 0, 0) }
309 /// Allocates an empty builder with capacity for the specified keys, values, and updates.
310 ///
311 /// They represent respectively the number of distinct `key`, `(key, val)`, and total updates.
312 fn with_capacity(keys: usize, vals: usize, upds: usize) -> Self;
313 /// Adds a chunk of elements to the batch.
314 ///
315 /// Adds all elements from `chunk` to the builder and leaves `chunk` in an undefined state.
316 fn push(&mut self, chunk: &mut Self::Input);
317 /// Completes building and returns the batch.
318 fn done(self, description: Description<Self::Time>) -> Self::Output;
319
320 /// Builds a batch from a chain of updates corresponding to the indicated lower and upper bounds.
321 ///
322 /// This method relies on the chain only containing updates greater or equal to the lower frontier,
323 /// and not greater or equal to the upper frontier, as encoded in the description. Chains must also
324 /// be sorted and consolidated.
325 fn seal(chain: &mut Vec<Self::Input>, description: Description<Self::Time>) -> Self::Output;
326}
327
328/// Represents a merge in progress.
329pub trait Merger<Output: Batch> {
330 /// Creates a new merger to merge the supplied batches, optionally compacting
331 /// up to the supplied frontier.
332 fn new(source1: &Output, source2: &Output, compaction_frontier: AntichainRef<Output::Time>) -> Self;
333 /// Perform some amount of work, decrementing `fuel`.
334 ///
335 /// If `fuel` is non-zero after the call, the merging is complete and
336 /// one should call `done` to extract the merged results.
337 fn work(&mut self, source1: &Output, source2: &Output, fuel: &mut isize);
338 /// Extracts merged results.
339 ///
340 /// This method should only be called after `work` has been called and
341 /// has not brought `fuel` to zero. Otherwise, the merge is still in
342 /// progress.
343 fn done(self) -> Output;
344}
345
346
347/// Blanket implementations for reference counted batches.
348pub mod rc_blanket_impls {
349
350 use std::rc::Rc;
351
352 use timely::progress::{Antichain, frontier::AntichainRef};
353 use super::{Batch, BatchReader, Builder, Merger, Cursor, Description};
354
355 impl<B: BatchReader> BatchReader for Rc<B> {
356 type Key<'a> = B::Key<'a>;
357 type Val<'a> = B::Val<'a>;
358 type Time = B::Time;
359 type TimeGat<'a> = B::TimeGat<'a>;
360 type Diff = B::Diff;
361 type DiffGat<'a> = B::DiffGat<'a>;
362
363 /// The type used to enumerate the batch's contents.
364 type Cursor = RcBatchCursor<B::Cursor>;
365 /// Acquires a cursor to the batch's contents.
366 fn cursor(&self) -> Self::Cursor {
367 RcBatchCursor::new((**self).cursor())
368 }
369
370 /// The number of updates in the batch.
371 fn len(&self) -> usize { (**self).len() }
372 /// Describes the times of the updates in the batch.
373 fn description(&self) -> &Description<Self::Time> { (**self).description() }
374 }
375
376 /// Wrapper to provide cursor to nested scope.
377 pub struct RcBatchCursor<C> {
378 cursor: C,
379 }
380
381 impl<C> RcBatchCursor<C> {
382 fn new(cursor: C) -> Self {
383 RcBatchCursor {
384 cursor,
385 }
386 }
387 }
388
389 impl<C: Cursor> Cursor for RcBatchCursor<C> {
390
391 type Key<'a> = C::Key<'a>;
392 type Val<'a> = C::Val<'a>;
393 type Time = C::Time;
394 type TimeGat<'a> = C::TimeGat<'a>;
395 type Diff = C::Diff;
396 type DiffGat<'a> = C::DiffGat<'a>;
397
398 type Storage = Rc<C::Storage>;
399
400 #[inline] fn key_valid(&self, storage: &Self::Storage) -> bool { self.cursor.key_valid(storage) }
401 #[inline] fn val_valid(&self, storage: &Self::Storage) -> bool { self.cursor.val_valid(storage) }
402
403 #[inline] fn key<'a>(&self, storage: &'a Self::Storage) -> Self::Key<'a> { self.cursor.key(storage) }
404 #[inline] fn val<'a>(&self, storage: &'a Self::Storage) -> Self::Val<'a> { self.cursor.val(storage) }
405
406 #[inline]
407 fn map_times<L: FnMut(Self::TimeGat<'_>, Self::DiffGat<'_>)>(&mut self, storage: &Self::Storage, logic: L) {
408 self.cursor.map_times(storage, logic)
409 }
410
411 #[inline] fn step_key(&mut self, storage: &Self::Storage) { self.cursor.step_key(storage) }
412 #[inline] fn seek_key(&mut self, storage: &Self::Storage, key: Self::Key<'_>) { self.cursor.seek_key(storage, key) }
413
414 #[inline] fn step_val(&mut self, storage: &Self::Storage) { self.cursor.step_val(storage) }
415 #[inline] fn seek_val(&mut self, storage: &Self::Storage, val: Self::Val<'_>) { self.cursor.seek_val(storage, val) }
416
417 #[inline] fn rewind_keys(&mut self, storage: &Self::Storage) { self.cursor.rewind_keys(storage) }
418 #[inline] fn rewind_vals(&mut self, storage: &Self::Storage) { self.cursor.rewind_vals(storage) }
419 }
420
421 /// An immutable collection of updates.
422 impl<B: Batch> Batch for Rc<B> {
423 type Merger = RcMerger<B>;
424 fn empty(lower: Antichain<Self::Time>, upper: Antichain<Self::Time>) -> Self {
425 Rc::new(B::empty(lower, upper))
426 }
427 }
428
429 /// Wrapper type for building reference counted batches.
430 pub struct RcBuilder<B: Builder> { builder: B }
431
432 /// Functionality for building batches from ordered update sequences.
433 impl<B: Builder> Builder for RcBuilder<B> {
434 type Input = B::Input;
435 type Time = B::Time;
436 type Output = Rc<B::Output>;
437 fn with_capacity(keys: usize, vals: usize, upds: usize) -> Self { RcBuilder { builder: B::with_capacity(keys, vals, upds) } }
438 fn push(&mut self, input: &mut Self::Input) { self.builder.push(input) }
439 fn done(self, description: Description<Self::Time>) -> Rc<B::Output> { Rc::new(self.builder.done(description)) }
440 fn seal(chain: &mut Vec<Self::Input>, description: Description<Self::Time>) -> Self::Output {
441 Rc::new(B::seal(chain, description))
442 }
443 }
444
445 /// Wrapper type for merging reference counted batches.
446 pub struct RcMerger<B:Batch> { merger: B::Merger }
447
448 /// Represents a merge in progress.
449 impl<B:Batch> Merger<Rc<B>> for RcMerger<B> {
450 fn new(source1: &Rc<B>, source2: &Rc<B>, compaction_frontier: AntichainRef<B::Time>) -> Self { RcMerger { merger: B::begin_merge(source1, source2, compaction_frontier) } }
451 fn work(&mut self, source1: &Rc<B>, source2: &Rc<B>, fuel: &mut isize) { self.merger.work(source1, source2, fuel) }
452 fn done(self) -> Rc<B> { Rc::new(self.merger.done()) }
453 }
454}