Skip to main content

mz_compute/logging/
differential.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Logging dataflows for events generated by differential dataflow.
11
12use std::cell::RefCell;
13use std::collections::BTreeMap;
14use std::rc::Rc;
15use std::time::Duration;
16
17use differential_dataflow::consolidation::ConsolidatingContainerBuilder;
18use differential_dataflow::logging::{
19    BatchEvent, BatcherEvent, DifferentialEvent, DropEvent, MergeEvent, TraceShare,
20};
21use mz_ore::cast::CastFrom;
22use mz_repr::{Datum, Diff, Timestamp};
23use mz_row_spine::RowRowBuilder;
24use mz_timely_util::columnar::batcher;
25use mz_timely_util::columnar::builder::ColumnBuilder;
26use mz_timely_util::columnar::{Col2ValBatcher, columnar_exchange};
27use mz_timely_util::replay::MzReplay;
28use timely::dataflow::channels::pact::{ExchangeCore, Pipeline};
29use timely::dataflow::operators::InputCapability;
30use timely::dataflow::operators::generic::builder_rc::OperatorBuilder;
31use timely::dataflow::operators::generic::operator::empty;
32use timely::dataflow::operators::generic::{OutputBuilder, Session};
33use timely::dataflow::{Scope, StreamVec};
34
35use crate::extensions::arrange::MzArrangeCore;
36use crate::logging::compute::{ArrangementHeapSizeOperatorDrop, ComputeEvent};
37use crate::logging::{
38    DifferentialLog, EventQueue, LogCollection, LogVariant, SharedLoggingState,
39    consolidate_and_pack,
40};
41use crate::typedefs::ConsolidateBatcher;
42use crate::typedefs::RowRowSpine;
43
44/// The return type of [`construct`].
45pub(super) struct Return {
46    /// Collections to export.
47    pub collections: BTreeMap<LogVariant, LogCollection>,
48}
49
50/// Constructs the logging dataflow fragment for differential logs.
51///
52/// Params
53/// * `scope`: The Timely scope hosting the log analysis dataflow.
54/// * `config`: Logging configuration
55/// * `event_queue`: The source to read log events from.
56/// * `shared_state`: Shared state across all logging dataflow fragments.
57pub(super) fn construct(
58    scope: Scope<'_, Timestamp>,
59    config: &mz_compute_client::logging::LoggingConfig,
60    event_queue: EventQueue<Vec<(Duration, DifferentialEvent)>>,
61    shared_state: Rc<RefCell<SharedLoggingState>>,
62) -> Return {
63    let logging_interval_ms = std::cmp::max(1, config.interval.as_millis());
64
65    scope.scoped("differential logging", move |scope| {
66        let enable_logging = config.enable_logging;
67        let (logs, token) = if enable_logging {
68            event_queue.links.mz_replay(
69                scope,
70                "differential logs",
71                config.interval,
72                event_queue.activator,
73            )
74        } else {
75            let token: Rc<dyn std::any::Any> = Rc::new(Box::new(()));
76            (empty(scope), token)
77        };
78
79        // Build a demux operator that splits the replayed event stream up into the separate
80        // logging streams.
81        let mut demux =
82            OperatorBuilder::new("Differential Logging Demux".to_string(), scope.clone());
83        let mut input = demux.new_input(logs, Pipeline);
84        let (batches_out, batches) = demux.new_output();
85        let (records_out, records) = demux.new_output();
86        let (sharing_out, sharing) = demux.new_output();
87        let (batcher_records_out, batcher_records) = demux.new_output();
88        let (batcher_size_out, batcher_size) = demux.new_output();
89        let (batcher_capacity_out, batcher_capacity) = demux.new_output();
90        let (batcher_allocations_out, batcher_allocations) = demux.new_output();
91
92        let mut batches_out = OutputBuilder::from(batches_out);
93        let mut records_out = OutputBuilder::from(records_out);
94        let mut sharing_out = OutputBuilder::from(sharing_out);
95        let mut batcher_records_out = OutputBuilder::from(batcher_records_out);
96        let mut batcher_size_out = OutputBuilder::from(batcher_size_out);
97        let mut batcher_capacity_out = OutputBuilder::from(batcher_capacity_out);
98        let mut batcher_allocations_out = OutputBuilder::from(batcher_allocations_out);
99
100        let mut demux_state = Default::default();
101        demux.build(move |_capability| {
102            move |_frontiers| {
103                let mut batches = batches_out.activate();
104                let mut records = records_out.activate();
105                let mut sharing = sharing_out.activate();
106                let mut batcher_records = batcher_records_out.activate();
107                let mut batcher_size = batcher_size_out.activate();
108                let mut batcher_capacity = batcher_capacity_out.activate();
109                let mut batcher_allocations = batcher_allocations_out.activate();
110
111                input.for_each_stamp(|cap, data| {
112                    let mut output_buffers = DemuxOutput {
113                        batches: batches.session_with_builder(&cap),
114                        records: records.session_with_builder(&cap),
115                        sharing: sharing.session_with_builder(&cap),
116                        batcher_records: batcher_records.session_with_builder(&cap),
117                        batcher_size: batcher_size.session_with_builder(&cap),
118                        batcher_capacity: batcher_capacity.session_with_builder(&cap),
119                        batcher_allocations: batcher_allocations.session_with_builder(&cap),
120                    };
121
122                    for (time, event) in data.flat_map(|data: &mut Vec<_>| data.drain(..)) {
123                        DemuxHandler {
124                            state: &mut demux_state,
125                            output: &mut output_buffers,
126                            logging_interval_ms,
127                            time,
128                            shared_state: &mut shared_state.borrow_mut(),
129                        }
130                        .handle(event);
131                    }
132                });
133            }
134        });
135
136        // We're lucky and the differential logs all have the same stream format, so just implement
137        // the call once.
138        fn stream_to_collection<'scope>(
139            input: StreamVec<'scope, Timestamp, ((usize, ()), Timestamp, Diff)>,
140            log: DifferentialLog,
141            worker_id: usize,
142        ) -> timely::dataflow::Stream<
143            'scope,
144            Timestamp,
145            mz_timely_util::columnar::Column<((mz_repr::Row, mz_repr::Row), Timestamp, Diff)>,
146        > {
147            consolidate_and_pack::<ConsolidateBatcher<_, _, _>, ColumnBuilder<_>, _, _, _, _>(
148                input,
149                log,
150                move |data, packer, session| {
151                    for ((op, ()), time, diff) in data.iter() {
152                        let data = packer.pack_slice(&[
153                            Datum::UInt64(u64::cast_from(*op)),
154                            Datum::UInt64(u64::cast_from(worker_id)),
155                        ]);
156                        session.give((data, *time, *diff))
157                    }
158                },
159            )
160        }
161        let worker_id = scope.index();
162
163        // Encode the contents of each logging stream into its expected `Row` format.
164        let arrangement_batches = stream_to_collection(batches, ArrangementBatches, worker_id);
165        let arrangement_records = stream_to_collection(records, ArrangementRecords, worker_id);
166        let sharing = stream_to_collection(sharing, Sharing, worker_id);
167        let batcher_records = stream_to_collection(batcher_records, BatcherRecords, worker_id);
168        let batcher_size = stream_to_collection(batcher_size, BatcherSize, worker_id);
169        let batcher_capacity = stream_to_collection(batcher_capacity, BatcherCapacity, worker_id);
170        let batcher_allocations =
171            stream_to_collection(batcher_allocations, BatcherAllocations, worker_id);
172
173        use DifferentialLog::*;
174        let logs = [
175            (ArrangementBatches, arrangement_batches),
176            (ArrangementRecords, arrangement_records),
177            (Sharing, sharing),
178            (BatcherRecords, batcher_records),
179            (BatcherSize, batcher_size),
180            (BatcherCapacity, batcher_capacity),
181            (BatcherAllocations, batcher_allocations),
182        ];
183
184        // Build the output arrangements.
185        let mut collections = BTreeMap::new();
186        for (variant, collection) in logs {
187            let variant = LogVariant::Differential(variant);
188            if config.index_logs.contains_key(&variant) {
189                let exchange = ExchangeCore::<ColumnBuilder<_>, _>::new_core(
190                    columnar_exchange::<mz_repr::Row, mz_repr::Row, Timestamp, mz_repr::Diff>,
191                );
192                let trace = collection
193                    .mz_arrange_core::<
194                        _,
195                        Col2ValBatcher<_, _, _, _, batcher::Chunker<_>, RowRowBuilder<_, _>>,
196                        RowRowSpine<_, _>,
197                    >(exchange, &format!("Arrange {variant:?}"))
198                    .trace;
199                let collection = LogCollection {
200                    trace,
201                    token: Rc::clone(&token),
202                };
203                collections.insert(variant, collection);
204            }
205        }
206
207        Return { collections }
208    })
209}
210
211type OutputSession<'a, 'b, D> = Session<
212    'a,
213    'b,
214    Timestamp,
215    ConsolidatingContainerBuilder<Vec<(D, Timestamp, Diff)>>,
216    InputCapability<Timestamp>,
217>;
218
219/// Bundled output buffers used by the demux operator.
220struct DemuxOutput<'a, 'b> {
221    batches: OutputSession<'a, 'b, (usize, ())>,
222    records: OutputSession<'a, 'b, (usize, ())>,
223    sharing: OutputSession<'a, 'b, (usize, ())>,
224    batcher_records: OutputSession<'a, 'b, (usize, ())>,
225    batcher_size: OutputSession<'a, 'b, (usize, ())>,
226    batcher_capacity: OutputSession<'a, 'b, (usize, ())>,
227    batcher_allocations: OutputSession<'a, 'b, (usize, ())>,
228}
229
230/// State maintained by the demux operator.
231#[derive(Default)]
232struct DemuxState {
233    /// Arrangement trace sharing
234    sharing: BTreeMap<usize, usize>,
235}
236
237/// Event handler of the demux operator.
238struct DemuxHandler<'a, 'b, 'c> {
239    /// State kept by the demux operator
240    state: &'a mut DemuxState,
241    /// Demux output buffers.
242    output: &'a mut DemuxOutput<'b, 'c>,
243    /// The logging interval specifying the time granularity for the updates.
244    logging_interval_ms: u128,
245    /// The current event time.
246    time: Duration,
247    /// State shared across log receivers.
248    shared_state: &'a mut SharedLoggingState,
249}
250
251impl DemuxHandler<'_, '_, '_> {
252    /// Return the timestamp associated with the current event, based on the event time and the
253    /// logging interval.
254    fn ts(&self) -> Timestamp {
255        let time_ms = self.time.as_millis();
256        let interval = self.logging_interval_ms;
257        let rounded = (time_ms / interval + 1) * interval;
258        rounded.try_into().expect("must fit")
259    }
260
261    /// Handle the given differential event.
262    fn handle(&mut self, event: DifferentialEvent) {
263        use DifferentialEvent::*;
264
265        match event {
266            Batch(e) => self.handle_batch(e),
267            Merge(e) => self.handle_merge(e),
268            Drop(e) => self.handle_drop(e),
269            TraceShare(e) => self.handle_trace_share(e),
270            Batcher(e) => self.handle_batcher_event(e),
271            MergeShortfall(_) => (),
272        }
273    }
274
275    fn handle_batch(&mut self, event: BatchEvent) {
276        let ts = self.ts();
277        let operator_id = event.operator;
278        self.output.batches.give(((operator_id, ()), ts, Diff::ONE));
279
280        let diff = Diff::try_from(event.length).expect("must fit");
281        self.output.records.give(((operator_id, ()), ts, diff));
282        self.notify_arrangement_size(operator_id);
283    }
284
285    fn handle_merge(&mut self, event: MergeEvent) {
286        let Some(done) = event.complete else { return };
287
288        let ts = self.ts();
289        let operator_id = event.operator;
290        self.output
291            .batches
292            .give(((operator_id, ()), ts, Diff::MINUS_ONE));
293
294        let diff = Diff::try_from(done).expect("must fit")
295            - Diff::try_from(event.length1 + event.length2).expect("must fit");
296        if diff != Diff::ZERO {
297            self.output.records.give(((operator_id, ()), ts, diff));
298        }
299        self.notify_arrangement_size(operator_id);
300    }
301
302    fn handle_drop(&mut self, event: DropEvent) {
303        let ts = self.ts();
304        let operator_id = event.operator;
305        self.output
306            .batches
307            .give(((operator_id, ()), ts, Diff::MINUS_ONE));
308
309        let diff = -Diff::try_from(event.length).expect("must fit");
310        if diff != Diff::ZERO {
311            self.output.records.give(((operator_id, ()), ts, diff));
312        }
313        self.notify_arrangement_size(operator_id);
314    }
315
316    fn handle_trace_share(&mut self, event: TraceShare) {
317        let ts = self.ts();
318        let operator_id = event.operator;
319        let diff = Diff::cast_from(event.diff);
320        mz_ore::soft_assert_ne_no_log!(diff, Diff::ZERO);
321        self.output.sharing.give(((operator_id, ()), ts, diff));
322
323        let sharing = self.state.sharing.entry(operator_id).or_default();
324        *sharing = (Diff::try_from(*sharing).expect("must fit") + diff)
325            .into_inner()
326            .try_into()
327            .expect("under/overflow");
328        if *sharing == 0 {
329            self.state.sharing.remove(&operator_id);
330            self.shared_state.compute_logger.as_ref().map(|logger| {
331                logger.log(&ComputeEvent::ArrangementHeapSizeOperatorDrop(
332                    ArrangementHeapSizeOperatorDrop { operator_id },
333                ))
334            });
335        }
336    }
337
338    fn handle_batcher_event(&mut self, event: BatcherEvent) {
339        let ts = self.ts();
340        let operator_id = event.operator;
341        let records_diff = Diff::cast_from(event.records_diff);
342        let size_diff = Diff::cast_from(event.size_diff);
343        let capacity_diff = Diff::cast_from(event.capacity_diff);
344        let allocations_diff = Diff::cast_from(event.allocations_diff);
345        self.output
346            .batcher_records
347            .give(((operator_id, ()), ts, records_diff));
348        self.output
349            .batcher_size
350            .give(((operator_id, ()), ts, size_diff));
351        self.output
352            .batcher_capacity
353            .give(((operator_id, ()), ts, capacity_diff));
354        self.output
355            .batcher_allocations
356            .give(((operator_id, ()), ts, allocations_diff));
357    }
358
359    fn notify_arrangement_size(&self, operator: usize) {
360        // While every arrangement should have a corresponding arrangement size operator,
361        // we have no guarantee that it already/still exists. Otherwise we could print a warning
362        // here, but it's difficult to implement without maintaining state for a longer period than
363        // while the arrangement actually exists.
364        if let Some(activator) = self.shared_state.arrangement_size_activators.get(&operator) {
365            activator.activate();
366        }
367    }
368}