1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
//! Group transformer operators that map multiple input records
//! into multiple output records.
use crate::{
Circuit, DynZWeight, Position, RootCircuit, Stream,
algebra::{HasZero, IndexedZSet, OrdIndexedZSet, ZCursor},
circuit::{
Scope,
metadata::{BatchSizeStats, INPUT_BATCHES_STATS, OUTPUT_BATCHES_STATS, OperatorMeta},
operator_traits::Operator,
splitter_output_chunk_size,
},
dynamic::{DataTrait, DynUnit, Factory},
operator::{
async_stream_operators::{StreamingTernaryOperator, StreamingTernaryWrapper},
dynamic::{accumulate_trace::AccumulateTraceFeedback, trace::TraceBounds},
},
trace::{
BatchFactories, BatchReader, BatchReaderFactories, Builder, Cursor,
OrdIndexedWSetFactories, Spine, TupleBuilder,
cursor::{CursorEmpty, CursorGroup, CursorPair},
spine_async::WithSnapshot,
},
};
use std::{borrow::Cow, cell::RefCell, marker::PhantomData, ops::Neg, rc::Rc};
mod lag;
mod topk;
#[cfg(test)]
mod test;
use async_stream::stream;
use dyn_clone::clone_box;
use futures::Stream as AsyncStream;
use crate::dynamic::{ClonableTrait, Erase};
pub use lag::{LagCustomOrdFactories, LagFactories};
pub use topk::{TopKCustomOrdFactories, TopKFactories, TopKRankCustomOrdFactories};
/// Specifies the order in which a group transformer produces output tuples.
#[derive(PartialEq, Eq)]
pub enum Monotonicity {
/// Transformer produces outputs in ascending order. Output tuples
/// can be pushed directly to a `Builder`.
Ascending,
/// Transformer produces outputs in descending order. Once all outputs
/// have been produced, they can be pushed to a `Builder` in reverse
/// order.
Descending,
/// Transformer does not guarantee an particular order of output tuples.
/// Outputs must be sorted before pushing them to a `Builder`.
#[allow(dead_code)]
Unordered,
}
/// Defines an incremental transformation of multiple input records
/// into multiple output records.
///
/// Group transformers are a generalization of aggregators: while an
/// aggregator maps a group of values into a single aggregate value,
/// a group transformer maps multiple input values into multiple output
/// values. Examples are the `top-k` transformer that returns
/// `k` largest values in the group and the `row-number` transformer
/// that attaches index to each input value according to ascdending or
/// descending order.
pub trait GroupTransformer<I: ?Sized, O: ?Sized>: 'static {
/// Transformer name.
fn name(&self) -> &str;
/// Output ordering guaranteed by this transformer.
fn monotonicity(&self) -> Monotonicity;
/// Compute changes to the output group given changes to the input group.
/// Produces changes to the output group by invoking `output_cb` for each
/// output update in the order consistent with `self.monotonicity()`.
///
/// # Arguments
///
/// * `input_delta` - cursor over changes to the input group.
/// * `input_trace` - cursor over the entire contents of the input group
/// after the previous clock tick.
/// * `output_trace` - cursor over the entire contents of the output group
/// after the previous clock tick.
/// * `output_cb` - callback invoked for each output update.
fn transform(
&mut self,
input_delta: &mut dyn ZCursor<I, DynUnit, ()>,
input_trace: &mut dyn ZCursor<I, DynUnit, ()>,
output_trace: &mut dyn ZCursor<O, DynUnit, ()>,
output_cb: &mut dyn FnMut(&mut O, &mut DynZWeight),
);
}
/// Non-incremental group transformer.
///
/// This version of the group transformer trait computes the
/// complete contents of the output group at each clock tick.
/// It is easier to implement than [`GroupTransformer`], which
/// constructs the output group incrementally. It is generally
/// less efficient than an optimized incremental implementation
/// as it requires scanning the entire input group. One notable
/// exception is `top-k` with a small value of `k`, which only
/// requires scanning `k` top elements.
///
/// A transformer that implements this trait can be used to build
/// an incremental group transformer by wrapping it in
/// [`DiffGroupTransformer`].
pub trait NonIncrementalGroupTransformer<I: ?Sized, O: ?Sized>: 'static {
/// Transformer name.
fn name(&self) -> &str;
/// Output ordering guaranteed by this transformer.
fn monotonicity(&self) -> Monotonicity;
/// Compute the complete contents of the output group given the complete
/// contents of the input group.
/// Produces changes to the output group by invoking `output_cb` for each
/// output update in the order consistent with `self.monotonicity()`.
///
/// # Arguments
///
/// * `cursor` - cursor over the contents of the input group.
/// * `output_cb` - callback invoked for each output record.
fn transform<C, CB>(&mut self, cursor: &mut C, output_cb: CB)
where
C: Cursor<I, DynUnit, (), DynZWeight>,
CB: FnMut(&mut O, &mut DynZWeight);
}
/// Incremental group transformer that wraps a non-incremental transformer.
///
/// This object implements the incremental group transformer API
/// ([`GroupTransformer`]) on top of a non-incremental transformer
/// ([`NonIncrementalGroupTransformer`]). It works by using the underlying
/// non-incremental transformer to compute the complete output group on
/// each clock tick and subtracting the previous contents of the output
/// group.
// TODO: This implementation maintains the trace of both input and output
// collections. An alternative implementation could trade memory for CPU
// by maintaining only the input trace and computing both current and
// previous outputs every time.
pub struct DiffGroupTransformer<I: DataTrait + ?Sized, O: DataTrait + ?Sized, T> {
output_factory: &'static dyn Factory<O>,
transformer: T,
_phantom: PhantomData<fn(&I, &O)>,
}
impl<I: DataTrait + ?Sized, O: DataTrait + ?Sized, T> DiffGroupTransformer<I, O, T> {
fn new(output_factory: &'static dyn Factory<O>, transformer: T) -> Self {
Self {
output_factory,
transformer,
_phantom: PhantomData,
}
}
}
impl<I, O, T> GroupTransformer<I, O> for DiffGroupTransformer<I, O, T>
where
I: DataTrait + ?Sized,
O: DataTrait + ?Sized,
T: NonIncrementalGroupTransformer<I, O>,
{
fn name(&self) -> &str {
self.transformer.name()
}
fn monotonicity(&self) -> Monotonicity {
self.transformer.monotonicity()
}
fn transform(
&mut self,
input_delta: &mut dyn ZCursor<I, DynUnit, ()>,
input_trace: &mut dyn ZCursor<I, DynUnit, ()>,
output_trace: &mut dyn ZCursor<O, DynUnit, ()>,
output_cb: &mut dyn FnMut(&mut O, &mut DynZWeight),
) {
let mut key = self.output_factory.default_box();
match self.transformer.monotonicity() {
Monotonicity::Ascending => {
// Transformer produces outputs in ascending order. Interleave them
// with retractions from the output trace to maintain ascending order
// across insertions and retractions.
self.transformer.transform(
&mut CursorPair::new(input_delta, input_trace),
|v, w| {
while output_trace.key_valid() && output_trace.key() < v {
let ow = **output_trace.weight();
debug_assert!(ow != 0);
output_trace.key().clone_to(&mut key);
output_cb(&mut key, ow.neg().erase_mut());
output_trace.step_key();
}
if output_trace.key_valid() && output_trace.key() == v {
let mut w = **w + output_trace.weight().neg();
if !w.is_zero() {
output_trace.key().clone_to(&mut key);
output_cb(&mut key, w.erase_mut());
}
output_trace.step_key();
} else {
output_cb(v, w);
}
},
);
// Output remaining retractions in the output trace.
while output_trace.key_valid() {
let w = **output_trace.weight();
debug_assert!(w != 0);
output_trace.key().clone_to(&mut key);
output_cb(&mut key, w.neg().erase_mut());
output_trace.step_key();
}
}
Monotonicity::Descending => {
// Transformer produces outputs in descending order. Interleave them
// with retractions from the output trace to maintain descending order
// across insertions and retractions.
output_trace.fast_forward_keys();
self.transformer.transform(
&mut CursorPair::new(input_delta, input_trace),
|v, w| {
while output_trace.key_valid() && output_trace.key() > v {
let ow = **output_trace.weight();
debug_assert!(ow != 0);
output_trace.key().clone_to(&mut key);
output_cb(&mut key, ow.neg().erase_mut());
output_trace.step_key_reverse();
}
if output_trace.key_valid() && output_trace.key() == v {
let mut w = **w + output_trace.weight().neg();
if !w.is_zero() {
output_trace.key().clone_to(&mut key);
output_cb(&mut key, w.erase_mut());
}
output_trace.step_key_reverse();
} else {
output_cb(v, w);
}
},
);
// Output remaining retractions in the output trace.
while output_trace.key_valid() {
let w = **output_trace.weight();
debug_assert!(w != 0);
output_trace.key().clone_to(&mut key);
output_cb(&mut key, w.neg().erase_mut());
output_trace.step_key_reverse();
}
}
Monotonicity::Unordered => {
// Transformer produces unordered outputs.
self.transformer
.transform(&mut CursorPair::new(input_delta, input_trace), |v, w| {
output_cb(v, w)
});
// Output retractions in output trace.
while output_trace.key_valid() {
let w = **output_trace.weight();
debug_assert!(w != 0);
output_trace.key().clone_to(&mut key);
output_cb(&mut key, w.neg().erase_mut());
output_trace.step_key();
}
}
}
}
}
impl<B> Stream<RootCircuit, B>
where
B: IndexedZSet + Send,
{
/// Apply group `transformer` to each partition in the input stream.
///
/// Applies group transformer `transformer` to values associated with
/// each key in the input stream.
fn dyn_group_transform<OV>(
&self,
persistent_id: Option<&str>,
input_factories: &B::Factories,
output_factories: &OrdIndexedWSetFactories<B::Key, OV, DynZWeight>,
transformer: Box<dyn GroupTransformer<B::Val, OV>>,
) -> Stream<RootCircuit, OrdIndexedZSet<B::Key, OV>>
where
OV: DataTrait + ?Sized,
{
self.dyn_group_transform_generic(
persistent_id,
input_factories,
output_factories,
transformer,
)
}
/// Like [`group_transform`](`Self::group_transform`), but can output any
/// indexed Z-set, not just [`OrdIndexedZSet`]
fn dyn_group_transform_generic<OB>(
&self,
persistent_id: Option<&str>,
input_factories: &B::Factories,
output_factories: &OB::Factories,
transform: Box<dyn GroupTransformer<B::Val, OB::Val>>,
) -> Stream<RootCircuit, OB>
where
OB: IndexedZSet<Key = B::Key>,
{
let circuit = self.circuit();
let stream = self.dyn_shard(input_factories);
// ```
// ┌────────────────────────────────────────────┐
// │ │
// │ ▼
// stream│ ┌─────────────────────────┐ ┌──────────────┐ output ┌──────────────────┐
// ──────┴─►│integrate().delay_trace()├───────►│GroupTransform├────────────┤UntimedTraceAppend├───┐
// └─────────────────────────┘ └──────────────┘ └──────────────────┘ │
// ▲ ▲ │
// │ │ │
// │ delayed_trace ┌─┴──┐ │
// └────────────────────────┤Z^-1│◄────────────┘
// └────┘
// ```
let bounds = TraceBounds::unbounded();
let feedback = circuit.add_accumulate_integrate_trace_feedback::<Spine<OB>>(
persistent_id,
output_factories,
bounds,
);
let output = circuit
.add_ternary_operator(
StreamingTernaryWrapper::new(GroupTransform::new(output_factories, transform)),
&stream.dyn_accumulate(input_factories),
&stream
.dyn_accumulate_integrate_trace(input_factories)
.accumulate_delay_trace(),
&feedback.delayed_trace,
)
.mark_sharded();
feedback.connect(&output, output_factories);
output
}
}
struct GroupTransform<B, OB, T, OT>
where
B: IndexedZSet,
OB: IndexedZSet,
{
output_factories: OB::Factories,
transformer: RefCell<Box<dyn GroupTransformer<B::Val, OB::Val>>>,
// Input batch sizes.
input_batch_stats: RefCell<BatchSizeStats>,
// Output batch sizes.
output_batch_stats: RefCell<BatchSizeStats>,
_phantom: PhantomData<(B, OB, T, OT)>,
}
impl<B, OB, T, OT> GroupTransform<B, OB, T, OT>
where
B: IndexedZSet,
OB: IndexedZSet,
{
fn new(
output_factories: &OB::Factories,
transformer: Box<dyn GroupTransformer<B::Val, OB::Val>>,
) -> Self {
Self {
output_factories: output_factories.clone(),
transformer: RefCell::new(transformer),
input_batch_stats: RefCell::new(BatchSizeStats::new()),
output_batch_stats: RefCell::new(BatchSizeStats::new()),
_phantom: PhantomData,
}
}
}
impl<B, OB, T, OT> Operator for GroupTransform<B, OB, T, OT>
where
B: IndexedZSet,
OB: IndexedZSet,
T: 'static,
OT: 'static,
{
fn name(&self) -> Cow<'static, str> {
Cow::from(format!(
"GroupTransform({})",
self.transformer.borrow().name()
))
}
fn metadata(&self, meta: &mut OperatorMeta) {
meta.extend(metadata! {
INPUT_BATCHES_STATS => self.input_batch_stats.borrow().metadata(),
OUTPUT_BATCHES_STATS => self.output_batch_stats.borrow().metadata(),
});
}
fn fixedpoint(&self, _scope: Scope) -> bool {
true
}
}
impl<B, OB, T, OT> StreamingTernaryOperator<Option<Spine<B>>, T, OT, OB>
for GroupTransform<B, OB, T, OT>
where
B: IndexedZSet,
T: WithSnapshot<Batch = B> + Clone + 'static,
OB: IndexedZSet<Key = B::Key>,
OT: WithSnapshot<Batch = OB> + Clone + 'static,
{
fn eval(
self: Rc<Self>,
delta: Cow<'_, Option<Spine<B>>>,
input_trace: Cow<'_, T>,
output_trace: Cow<'_, OT>,
) -> impl AsyncStream<Item = (OB, bool, Option<Position>)> + 'static {
let delta = (*delta).as_ref().map(|b| b.ro_snapshot());
let chunk_size = splitter_output_chunk_size();
// We assume that delta.is_some() implies that the operator is being flushed,
// since the input integral is always flushed in the same step as delta and the
// delayed output integral is always flushed earlier.
let input_trace = if delta.is_some() {
Some(input_trace.ro_snapshot())
} else {
None
};
let output_trace = if delta.is_some() {
Some(output_trace.ro_snapshot())
} else {
None
};
stream! {
let Some(delta) = delta.as_ref() else {
yield (OB::dyn_empty(&self.output_factories), true, None);
return;
};
self.input_batch_stats.borrow_mut().add_batch(delta.len());
let mut delta_cursor = delta.cursor();
let mut input_trace_cursor = input_trace.unwrap().cursor();
let mut output_trace_cursor = output_trace.unwrap().cursor();
let capacity = std::cmp::min(delta.len(), chunk_size);
let mut builder = TupleBuilder::new(
&self.output_factories,
OB::Builder::with_capacity(&self.output_factories, capacity, capacity),
);
let mut buffer = self.output_factories.weighted_items_factory().default_box();
buffer.reserve(2 * chunk_size);
let monotonicity = self.transformer.borrow().monotonicity();
while delta_cursor.key_valid() {
let key = clone_box(delta_cursor.key());
let mut key2 = clone_box(key.as_ref());
let mut tuple = self.output_factories.weighted_item_factory().default_box();
// Output callback that pushes directly to builder.
let mut cb_asc = |val: &mut OB::Val, w: &mut B::R| {
key.clone_to(&mut key2);
// println!("val: {val:?}, w: {w:?}");
builder.push_vals(&mut key2, val, &mut (), w);
};
// Output callback that pushes to an intermediate buffer.
let mut cb_desc = |val: &mut OB::Val, w: &mut B::R| {
//println!("val: {val:?}, w: {w:?}");
let (kv, weight) = tuple.split_mut();
let (k, v) = kv.split_mut();
key.clone_to(k);
val.move_to(v);
w.move_to(weight);
buffer.push_val(&mut *tuple);
};
let cb = if monotonicity == Monotonicity::Ascending {
// Ascending transformer: push directly to builder.
&mut cb_asc as &mut dyn FnMut(&mut OB::Val, &mut B::R)
} else {
// Descending or unordered transformer: push to buffer.
&mut cb_desc as &mut dyn FnMut(&mut OB::Val, &mut B::R)
};
let mut delta_group_cursor = CursorGroup::new(&mut delta_cursor, ());
// I was not able to avoid 4-way code duplication below. Depending on
// whether `key` is found in the input and output trace, we must invoke
// `transformer.transform` with four different combinations of
// empty/non-empty cursors. Since the cursors have different types
// (`CursorEmpty` and `CursorGroup`), we can't bind them to the same
// variable.
if input_trace_cursor.seek_key_exact(&key, None) {
let mut input_group_cursor = CursorGroup::new(&mut input_trace_cursor, ());
if output_trace_cursor.seek_key_exact(&key, None) {
let mut output_group_cursor = CursorGroup::new(&mut output_trace_cursor, ());
self.transformer.borrow_mut().transform(
&mut delta_group_cursor,
&mut input_group_cursor,
&mut output_group_cursor,
cb,
);
} else {
let mut output_group_cursor =
CursorEmpty::new(self.output_factories.weight_factory());
self.transformer.borrow_mut().transform(
&mut delta_group_cursor,
&mut input_group_cursor,
&mut output_group_cursor,
cb,
);
};
} else {
let mut input_group_cursor =
CursorEmpty::new(self.output_factories.weight_factory());
if output_trace_cursor.seek_key_exact(&key, None) {
let mut output_group_cursor = CursorGroup::new(&mut output_trace_cursor, ());
self.transformer.borrow_mut().transform(
&mut delta_group_cursor,
&mut input_group_cursor,
&mut output_group_cursor,
cb,
);
} else {
let mut output_group_cursor =
CursorEmpty::new(self.output_factories.weight_factory());
self.transformer.borrow_mut().transform(
&mut CursorGroup::new(&mut delta_cursor, ()),
&mut input_group_cursor,
&mut output_group_cursor,
cb,
);
};
};
match monotonicity {
// Descending transformer: push tuples from `buffer` to builder
// in reverse order.
Monotonicity::Descending => {
for tuple in buffer.dyn_iter_mut().rev() {
builder.push(tuple)
}
}
// Unordered transformer: sort the buffer before pushing tuples
// to `builder`.
Monotonicity::Unordered => {
buffer.consolidate();
for tuple in buffer.dyn_iter_mut() {
builder.push(tuple)
}
}
// Ascending transformer: all updates already pushed to builder.
_ => {}
}
buffer.clear();
if builder.num_tuples() >= chunk_size {
let result = builder.done();
self.output_batch_stats.borrow_mut().add_batch(result.len());
yield (result, false, delta_cursor.position());
builder = TupleBuilder::new(
&self.output_factories,
OB::Builder::with_capacity(&self.output_factories, capacity, capacity),
);
}
delta_cursor.step_key();
}
let result = builder.done();
self.output_batch_stats.borrow_mut().add_batch(result.len());
yield (result, true, delta_cursor.position())
}
}
}