Skip to main content

mz_storage/render/
sources.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//! Logic related to the creation of dataflow sources.
11//!
12//! See [`render_source`] for more details.
13
14use std::collections::BTreeMap;
15use std::iter;
16use std::sync::Arc;
17
18use differential_dataflow::{AsCollection, VecCollection};
19use mz_ore::cast::CastLossy;
20use mz_persist_client::operators::shard_source::SnapshotMode;
21use mz_repr::{Datum, Diff, GlobalId, Row, RowPacker};
22use mz_storage_operators::persist_source;
23use mz_storage_operators::persist_source::Subtime;
24use mz_storage_types::controller::CollectionMetadata;
25use mz_storage_types::dyncfgs;
26use mz_storage_types::errors::{
27    DataflowError, DecodeError, EnvelopeError, UpsertError, UpsertNullKeyError, UpsertValueError,
28};
29use mz_storage_types::parameters::StorageMaxInflightBytesConfig;
30use mz_storage_types::sources::envelope::{KeyEnvelope, NoneEnvelope, UpsertEnvelope, UpsertStyle};
31use mz_storage_types::sources::*;
32use mz_timely_util::builder_async::PressOnDropButton;
33use mz_timely_util::operator::CollectionExt;
34use mz_timely_util::order::refine_antichain;
35use serde::{Deserialize, Serialize};
36use timely::container::CapacityContainerBuilder;
37use timely::dataflow::StreamVec;
38use timely::dataflow::operators::vec::Map;
39use timely::dataflow::operators::{ConnectLoop, Feedback, Leave, OkErr};
40use timely::dataflow::scope::Scope;
41use timely::progress::{Antichain, Timestamp};
42
43use crate::decode::{render_decode_cdcv2, render_decode_delimited};
44use crate::healthcheck::{HealthStatusMessage, StatusNamespace};
45use crate::source::types::{DecodeResult, SourceOutput, SourceRender};
46use crate::source::{self, RawSourceCreationConfig, SourceExportCreationConfig};
47use crate::upsert::{UpsertKey, UpsertSourceTime, UpsertValue};
48
49/// _Renders_ complete _differential_ collections
50/// that represent the final source and its errors
51/// as requested by the original `CREATE SOURCE` statement,
52/// encapsulated in the passed `SourceInstanceDesc`.
53///
54/// The first element in the returned tuple is the pair of Collections,
55/// the second is a type-erased token that will keep the source
56/// alive as long as it is not dropped.
57///
58/// This function is intended to implement the recipe described here:
59/// <https://github.com/MaterializeInc/materialize/blob/main/doc/developer/platform/architecture-storage.md#source-ingestion>
60pub fn render_source<'scope, 'root, C>(
61    scope: Scope<'scope, mz_repr::Timestamp>,
62    root_scope: Scope<'root, ()>,
63    dataflow_debug_name: &String,
64    connection: C,
65    description: IngestionDescription<CollectionMetadata>,
66    resume_stream: StreamVec<'scope, mz_repr::Timestamp, ()>,
67    storage_state: &crate::storage_state::StorageState,
68    base_source_config: RawSourceCreationConfig,
69) -> (
70    BTreeMap<
71        GlobalId,
72        (
73            VecCollection<'scope, mz_repr::Timestamp, Row, Diff>,
74            VecCollection<'scope, mz_repr::Timestamp, DataflowError, Diff>,
75        ),
76    >,
77    Vec<StreamVec<'root, (), HealthStatusMessage>>,
78    Vec<PressOnDropButton>,
79)
80where
81    C: SourceConnection + SourceRender + 'static,
82    C::Time: UpsertSourceTime,
83{
84    // Tokens that we should return from the method.
85    let mut needed_tokens = Vec::new();
86
87    // Note that this `render_source` attaches a single _instance_ of a source
88    // to the passed `Scope`, and this instance may be disabled if the
89    // source type does not support multiple instances. `render_source`
90    // is called on each timely worker as part of
91    // [`super::build_storage_dataflow`].
92
93    // A set of channels (1 per worker) used to signal rehydration being finished
94    // to raw sources. These are channels and not timely streams because they
95    // have to cross a scope boundary.
96    //
97    // Note that these will be entirely subsumed by full `hydration` backpressure,
98    // once that is implemented.
99    let (starter, mut start_signal) = tokio::sync::mpsc::channel::<()>(1);
100    let start_signal = async move {
101        let _ = start_signal.recv().await;
102    };
103
104    // Build the _raw_ ok and error sources using `create_raw_source` and the
105    // correct `SourceReader` implementations
106    let (exports, health, source_tokens) = source::create_raw_source(
107        scope,
108        root_scope,
109        storage_state,
110        resume_stream,
111        &base_source_config,
112        connection,
113        start_signal,
114    );
115
116    needed_tokens.extend(source_tokens);
117
118    let mut health_streams = Vec::with_capacity(exports.len() + 1);
119    health_streams.push(health);
120
121    let mut outputs = BTreeMap::new();
122    for (export_id, export) in exports {
123        type CB<C> = CapacityContainerBuilder<C>;
124        let (ok_stream, err_stream) =
125            export.map_fallible::<CB<_>, CB<_>, _, _, _>("export-demux-ok-err", |r| r);
126
127        // All sources should push their various error streams into this vector,
128        // whose contents will be concatenated and inserted along the collection.
129        // All subsources include the non-definite errors of the ingestion
130        let mut error_collections = Vec::new();
131
132        let data_config = base_source_config.source_exports[&export_id]
133            .data_config
134            .clone();
135        let (ok, extra_tokens, health_stream) = render_source_stream(
136            scope,
137            dataflow_debug_name,
138            export_id,
139            ok_stream,
140            data_config,
141            &description,
142            &mut error_collections,
143            storage_state,
144            &base_source_config,
145            starter.clone(),
146        );
147        needed_tokens.extend(extra_tokens);
148
149        // Flatten the error collections.
150        let err_collection = match error_collections.len() {
151            0 => err_stream,
152            _ => err_stream.concatenate(error_collections),
153        };
154
155        outputs.insert(export_id, (ok, err_collection));
156
157        health_streams.extend(health_stream.into_iter().map(|s| s.leave(root_scope)));
158    }
159    (outputs, health_streams, needed_tokens)
160}
161
162/// Completes the rendering of a particular source stream by applying decoding and envelope
163/// processing as necessary
164fn render_source_stream<'scope, FromTime>(
165    scope: Scope<'scope, mz_repr::Timestamp>,
166    dataflow_debug_name: &String,
167    export_id: GlobalId,
168    ok_source: VecCollection<'scope, mz_repr::Timestamp, SourceOutput<FromTime>, Diff>,
169    data_config: SourceExportDataConfig,
170    description: &IngestionDescription<CollectionMetadata>,
171    error_collections: &mut Vec<VecCollection<'scope, mz_repr::Timestamp, DataflowError, Diff>>,
172    storage_state: &crate::storage_state::StorageState,
173    base_source_config: &RawSourceCreationConfig,
174    rehydrated_token: impl std::any::Any + 'static,
175) -> (
176    VecCollection<'scope, mz_repr::Timestamp, Row, Diff>,
177    Vec<PressOnDropButton>,
178    Vec<StreamVec<'scope, mz_repr::Timestamp, HealthStatusMessage>>,
179)
180where
181    FromTime: Timestamp + Sync,
182    FromTime: UpsertSourceTime,
183{
184    let mut needed_tokens = vec![];
185
186    // Use the envelope and encoding configs for this particular source export
187    let SourceExportDataConfig { encoding, envelope } = data_config;
188
189    let SourceDesc {
190        connection: _,
191        timestamp_interval: _,
192    } = description.desc;
193
194    let (decoded_stream, decode_health) = match encoding {
195        None => (
196            ok_source.map(|r| DecodeResult {
197                // This is safe because the current set of sources produce
198                // either:
199                // 1. Non-nullable keys
200                // 2. No keys at all.
201                //
202                // Please see the comment on `key_envelope_no_encoding` in
203                // `mz_sql::plan::statement::ddl` for more details.
204                key: Some(Ok(r.key)),
205                value: Some(Ok(r.value)),
206                metadata: r.metadata,
207                from_time: r.from_time,
208            }),
209            None,
210        ),
211        Some(encoding) => {
212            let (decoded_stream, decode_health) = render_decode_delimited(
213                ok_source,
214                encoding.key,
215                encoding.value,
216                dataflow_debug_name.clone(),
217                storage_state.metrics.decode_defs.clone(),
218                storage_state.storage_configuration.clone(),
219            );
220            (decoded_stream, Some(decode_health))
221        }
222    };
223
224    // render envelopes
225    let (envelope_ok, envelope_health) = match &envelope {
226        SourceEnvelope::Upsert(upsert_envelope) => {
227            let upsert_input = upsert_commands(decoded_stream, upsert_envelope.clone());
228
229            let persist_clients = Arc::clone(&storage_state.persist_clients);
230            // TODO: Get this to work with the as_of.
231            let resume_upper = base_source_config.resume_uppers[&export_id].clone();
232
233            let upper_ts = resume_upper
234                .as_option()
235                .expect("resuming an already finished ingestion")
236                .clone();
237            let outer_mz_scope = scope.clone();
238            let (upsert, health_update) = scope.scoped(
239                &format!("upsert_rehydration_backpressure({})", export_id),
240                |scope| {
241                    let (previous, previous_token, feedback_handle, backpressure_metrics) = {
242                        let as_of = Antichain::from_elem(upper_ts.saturating_sub(1));
243
244                        let backpressure_max_inflight_bytes = get_backpressure_max_inflight_bytes(
245                            &storage_state
246                                .storage_configuration
247                                .parameters
248                                .storage_dataflow_max_inflight_bytes_config,
249                            &storage_state.instance_context.cluster_memory_limit,
250                        );
251
252                        let (feedback_handle, flow_control, backpressure_metrics) =
253                            if let Some(storage_dataflow_max_inflight_bytes) =
254                                backpressure_max_inflight_bytes
255                            {
256                                tracing::info!(
257                                    ?backpressure_max_inflight_bytes,
258                                    "timely-{} using backpressure in upsert for source {}",
259                                    base_source_config.worker_id,
260                                    export_id
261                                );
262                                if !storage_state
263                                    .storage_configuration
264                                    .parameters
265                                    .storage_dataflow_max_inflight_bytes_config
266                                    .disk_only
267                                    || storage_state.instance_context.scratch_directory.is_some()
268                                {
269                                    let (feedback_handle, feedback_data) =
270                                        scope.feedback(Default::default());
271
272                                    // TODO(guswynn): cleanup
273                                    let backpressure_metrics = Some(
274                                        base_source_config
275                                            .metrics
276                                            .get_backpressure_metrics(export_id, scope.index()),
277                                    );
278
279                                    (
280                                        Some(feedback_handle),
281                                        Some(persist_source::FlowControl {
282                                            progress_stream: feedback_data,
283                                            max_inflight_bytes: storage_dataflow_max_inflight_bytes,
284                                            summary: (Default::default(), Subtime::least_summary()),
285                                            metrics: backpressure_metrics.clone(),
286                                        }),
287                                        backpressure_metrics,
288                                    )
289                                } else {
290                                    (None, None, None)
291                                }
292                            } else {
293                                (None, None, None)
294                            };
295
296                        let storage_metadata = description.source_exports[&export_id]
297                            .storage_metadata
298                            .clone();
299
300                        let error_handler =
301                            storage_state.error_handler("upsert_rehydration", export_id);
302
303                        let (stream, tok) = persist_source::persist_source_core(
304                            outer_mz_scope,
305                            scope,
306                            export_id,
307                            persist_clients,
308                            storage_metadata,
309                            None,
310                            Some(as_of),
311                            SnapshotMode::Include,
312                            Antichain::new(),
313                            None,
314                            flow_control,
315                            false.then_some(|| unreachable!()),
316                            async {},
317                            error_handler,
318                        );
319                        (
320                            stream.as_collection(),
321                            Some(tok),
322                            feedback_handle,
323                            backpressure_metrics,
324                        )
325                    };
326
327                    let export_statistics = storage_state
328                        .aggregated_statistics
329                        .get_source(&export_id)
330                        .expect("statistics initialized")
331                        .clone();
332                    let export_config = SourceExportCreationConfig {
333                        id: export_id,
334                        worker_id: base_source_config.worker_id,
335                        metrics: base_source_config.metrics.clone(),
336                        source_statistics: export_statistics,
337                    };
338                    let (upsert, health_update, snapshot_progress, upsert_token) =
339                        if dyncfgs::ENABLE_UPSERT_V2
340                            .get(storage_state.storage_configuration.config_set())
341                        {
342                            // Resolved here, at operator construction, so the
343                            // dataflow keeps one stash flavor for its whole
344                            // life even if the flag flips underneath it.
345                            let stash_flavor =
346                                crate::upsert_continual_feedback_v2::UpsertStashFlavor::from_config(
347                                    storage_state.storage_configuration.config_set(),
348                                );
349                            crate::upsert::upsert_v2(
350                                upsert_input.enter(scope),
351                                upsert_envelope.clone(),
352                                refine_antichain(&resume_upper),
353                                previous,
354                                previous_token,
355                                export_config,
356                                backpressure_metrics,
357                                stash_flavor,
358                            )
359                        } else {
360                            crate::upsert::upsert(
361                                upsert_input.enter(scope),
362                                upsert_envelope.clone(),
363                                refine_antichain(&resume_upper),
364                                previous,
365                                previous_token,
366                                export_config,
367                                &storage_state.instance_context,
368                                &storage_state.storage_configuration,
369                                &storage_state.dataflow_parameters,
370                                backpressure_metrics,
371                            )
372                        };
373
374                    // Even though we register the `persist_sink` token at a top-level,
375                    // which will stop any data from being committed, we also register
376                    // a token for the `upsert` operator which may be in the middle of
377                    // rehydration processing the `persist_source` input above.
378                    needed_tokens.push(upsert_token);
379
380                    // If configured, delay raw sources until we rehydrate the upsert
381                    // source. Otherwise, drop the token, unblocking the sources at the
382                    // end rendering.
383                    if dyncfgs::DELAY_SOURCES_PAST_REHYDRATION
384                        .get(storage_state.storage_configuration.config_set())
385                    {
386                        crate::upsert::rehydration_finished(
387                            scope.clone(),
388                            base_source_config,
389                            rehydrated_token,
390                            refine_antichain(&resume_upper),
391                            snapshot_progress.clone(),
392                        );
393                    } else {
394                        drop(rehydrated_token)
395                    };
396
397                    // If backpressure from persist is enabled, we connect the upsert operator's
398                    // snapshot progress to the persist source feedback handle.
399                    if let Some(feedback_handle) = feedback_handle {
400                        snapshot_progress.connect_loop(feedback_handle);
401                    }
402
403                    (
404                        upsert.leave(outer_mz_scope),
405                        health_update
406                            .map(|(id, update)| HealthStatusMessage {
407                                id,
408                                namespace: StatusNamespace::Upsert,
409                                update,
410                            })
411                            .leave(outer_mz_scope),
412                    )
413                },
414            );
415
416            let (upsert_ok, upsert_err) = upsert.inner.ok_err(split_ok_err);
417            error_collections.push(upsert_err.as_collection());
418
419            (upsert_ok.as_collection(), Some(health_update))
420        }
421        SourceEnvelope::None(none_envelope) => {
422            let results = append_metadata_to_value(decoded_stream);
423
424            let flattened_stream = flatten_results_prepend_keys(none_envelope, results);
425
426            let (stream, errors) = flattened_stream.inner.ok_err(split_ok_err);
427
428            error_collections.push(errors.as_collection());
429            (stream.as_collection(), None)
430        }
431        SourceEnvelope::CdcV2 => {
432            let (oks, token) = render_decode_cdcv2(&decoded_stream);
433            needed_tokens.push(token);
434            (oks, None)
435        }
436    };
437
438    // Return the collections and any needed tokens.
439    let health = decode_health.into_iter().chain(envelope_health).collect();
440    (envelope_ok, needed_tokens, health)
441}
442
443// Returns the maximum limit of inflight bytes for backpressure based on given config
444// and the current cluster size
445fn get_backpressure_max_inflight_bytes(
446    inflight_bytes_config: &StorageMaxInflightBytesConfig,
447    cluster_memory_limit: &Option<usize>,
448) -> Option<usize> {
449    let StorageMaxInflightBytesConfig {
450        max_inflight_bytes_default,
451        max_inflight_bytes_cluster_size_fraction,
452        disk_only: _,
453    } = inflight_bytes_config;
454
455    // Will use backpressure only if the default inflight value is provided
456    if max_inflight_bytes_default.is_some() {
457        let current_cluster_max_bytes_limit =
458            cluster_memory_limit.as_ref().and_then(|cluster_memory| {
459                max_inflight_bytes_cluster_size_fraction.map(|fraction| {
460                    // We just need close the correct % of bytes here, so we just use lossy casts.
461                    usize::cast_lossy(f64::cast_lossy(*cluster_memory) * fraction)
462                })
463            });
464        current_cluster_max_bytes_limit.or(*max_inflight_bytes_default)
465    } else {
466        None
467    }
468}
469
470// TODO: Maybe we should finally move this to some central place and re-use. There seem to be
471// enough instances of this by now.
472fn split_ok_err<O, E, T, D>(x: (Result<O, E>, T, D)) -> Result<(O, T, D), (E, T, D)> {
473    match x {
474        (Ok(ok), ts, diff) => Ok((ok, ts, diff)),
475        (Err(err), ts, diff) => Err((err, ts, diff)),
476    }
477}
478
479/// After handling metadata insertion, we split streams into key/value parts for convenience
480#[derive(
481    Debug,
482    Clone,
483    Hash,
484    PartialEq,
485    Eq,
486    Ord,
487    PartialOrd,
488    Serialize,
489    Deserialize
490)]
491struct KV {
492    key: Option<Result<Row, DecodeError>>,
493    val: Option<Result<Row, DecodeError>>,
494}
495
496fn append_metadata_to_value<'scope, T: Timestamp, FromTime: Timestamp>(
497    results: VecCollection<'scope, T, DecodeResult<FromTime>, Diff>,
498) -> VecCollection<'scope, T, KV, Diff> {
499    results.map(move |res| {
500        let val = res.value.map(|val_result| {
501            val_result.map(|mut val| {
502                if !res.metadata.is_empty() {
503                    RowPacker::for_existing_row(&mut val).extend_by_row(&res.metadata);
504                }
505                val
506            })
507        });
508
509        KV { val, key: res.key }
510    })
511}
512
513/// Convert from streams of [`DecodeResult`] to UpsertCommands, inserting the Key according to [`KeyEnvelope`]
514fn upsert_commands<'scope, T: Timestamp, FromTime: Timestamp>(
515    input: VecCollection<'scope, T, DecodeResult<FromTime>, Diff>,
516    upsert_envelope: UpsertEnvelope,
517) -> VecCollection<'scope, T, (UpsertKey, Option<UpsertValue>, FromTime), Diff> {
518    let mut row_buf = Row::default();
519    input.map(move |result| {
520        let from_time = result.from_time;
521
522        let key = match result.key {
523            Some(Ok(key)) => Ok(key),
524            None => Err(UpsertError::NullKey(UpsertNullKeyError)),
525            Some(Err(err)) => Err(UpsertError::KeyDecode(err)),
526        };
527
528        // If we have a well-formed key we can continue, otherwise we're upserting an error
529        let key = match key {
530            Ok(key) => key,
531            Err(err) => match result.value {
532                Some(_) => {
533                    return (
534                        UpsertKey::from_key(Err(&err)),
535                        Some(Err(Box::new(err))),
536                        from_time,
537                    );
538                }
539                None => return (UpsertKey::from_key(Err(&err)), None, from_time),
540            },
541        };
542
543        // We can now apply the key envelope
544        let key_row = match upsert_envelope.style {
545            // flattened or debezium
546            UpsertStyle::Debezium { .. }
547            | UpsertStyle::Default(KeyEnvelope::Flattened)
548            | UpsertStyle::ValueErrInline {
549                key_envelope: KeyEnvelope::Flattened,
550                error_column: _,
551            } => key,
552            // named
553            UpsertStyle::Default(KeyEnvelope::Named(_))
554            | UpsertStyle::ValueErrInline {
555                key_envelope: KeyEnvelope::Named(_),
556                error_column: _,
557            } => {
558                if key.iter().nth(1).is_none() {
559                    key
560                } else {
561                    row_buf.packer().push_list(key.iter());
562                    row_buf.clone()
563                }
564            }
565            UpsertStyle::Default(KeyEnvelope::None)
566            | UpsertStyle::ValueErrInline {
567                key_envelope: KeyEnvelope::None,
568                error_column: _,
569            } => unreachable!(),
570        };
571
572        let key = UpsertKey::from_key(Ok(&key_row));
573
574        let metadata = result.metadata;
575
576        let value = match result.value {
577            Some(Ok(ref row)) => match upsert_envelope.style {
578                UpsertStyle::Debezium { after_idx } => match row.iter().nth(after_idx).unwrap() {
579                    Datum::List(after) => {
580                        let mut packer = row_buf.packer();
581                        packer.extend(after.iter());
582                        packer.extend_by_row(&metadata);
583                        Some(Ok(row_buf.clone()))
584                    }
585                    Datum::Null => None,
586                    d => panic!("type error: expected record, found {:?}", d),
587                },
588                UpsertStyle::Default(_) => {
589                    let mut packer = row_buf.packer();
590                    packer.extend_by_row(&key_row);
591                    packer.extend_by_row(row);
592                    packer.extend_by_row(&metadata);
593                    Some(Ok(row_buf.clone()))
594                }
595                UpsertStyle::ValueErrInline { .. } => {
596                    let mut packer = row_buf.packer();
597                    packer.extend_by_row(&key_row);
598                    // The 'error' column is null
599                    packer.push(Datum::Null);
600                    packer.extend_by_row(row);
601                    packer.extend_by_row(&metadata);
602                    Some(Ok(row_buf.clone()))
603                }
604            },
605            Some(Err(inner)) => {
606                match upsert_envelope.style {
607                    UpsertStyle::ValueErrInline { .. } => {
608                        let mut count = 0;
609                        // inline the error in the data output
610                        let err_string = inner.to_string();
611                        let mut packer = row_buf.packer();
612                        for datum in key_row.iter() {
613                            packer.push(datum);
614                            count += 1;
615                        }
616                        // The 'error' column is a record with a 'description' column
617                        packer.push_list(iter::once(Datum::String(&err_string)));
618                        count += 1;
619                        let metadata_len = metadata.as_row_ref().iter().count();
620                        // push nulls for all value columns
621                        packer.extend(
622                            iter::repeat(Datum::Null)
623                                .take(upsert_envelope.source_arity - count - metadata_len),
624                        );
625                        packer.extend_by_row(&metadata);
626                        Some(Ok(row_buf.clone()))
627                    }
628                    _ => Some(Err(Box::new(UpsertError::Value(UpsertValueError {
629                        for_key: key_row,
630                        inner,
631                    })))),
632                }
633            }
634            None => None,
635        };
636
637        (key, value, from_time)
638    })
639}
640
641/// Convert from streams of [`DecodeResult`] to Rows, inserting the Key according to [`KeyEnvelope`]
642fn flatten_results_prepend_keys<'scope, T: Timestamp>(
643    none_envelope: &NoneEnvelope,
644    results: VecCollection<'scope, T, KV, Diff>,
645) -> VecCollection<'scope, T, Result<Row, DataflowError>, Diff> {
646    let NoneEnvelope {
647        key_envelope,
648        key_arity,
649    } = none_envelope;
650
651    let null_key_columns = Row::pack_slice(&vec![Datum::Null; *key_arity]);
652
653    match key_envelope {
654        KeyEnvelope::None => {
655            results.flat_map(|KV { val, .. }| val.map(|result| result.map_err(Into::into)))
656        }
657        KeyEnvelope::Flattened => results
658            .flat_map(raise_key_value_errors)
659            .map(move |maybe_kv| {
660                maybe_kv.map(|(key, value)| {
661                    let mut key = key.unwrap_or_else(|| null_key_columns.clone());
662                    RowPacker::for_existing_row(&mut key).extend_by_row(&value);
663                    key
664                })
665            }),
666        KeyEnvelope::Named(_) => {
667            results
668                .flat_map(raise_key_value_errors)
669                .map(move |maybe_kv| {
670                    maybe_kv.map(|(key, value)| {
671                        let mut key = key.unwrap_or_else(|| null_key_columns.clone());
672                        // Named semantics rename a key that is a single column, and encode a
673                        // multi-column field as a struct with that name
674                        let row = if key.iter().nth(1).is_none() {
675                            RowPacker::for_existing_row(&mut key).extend_by_row(&value);
676                            key
677                        } else {
678                            let mut new_row = Row::default();
679                            let mut packer = new_row.packer();
680                            packer.push_list(key.iter());
681                            packer.extend_by_row(&value);
682                            new_row
683                        };
684                        row
685                    })
686                })
687        }
688    }
689}
690
691/// Handle possibly missing key or value portions of messages
692fn raise_key_value_errors(
693    KV { key, val }: KV,
694) -> Option<Result<(Option<Row>, Row), DataflowError>> {
695    match (key, val) {
696        (Some(Ok(key)), Some(Ok(value))) => Some(Ok((Some(key), value))),
697        (None, Some(Ok(value))) => Some(Ok((None, value))),
698        // always prioritize the value error if either or both have an error
699        (_, Some(Err(e))) => Some(Err(e.into())),
700        (Some(Err(e)), _) => Some(Err(e.into())),
701        (None, None) => None,
702        // TODO(petrosagg): these errors would be better grouped under an EnvelopeError enum
703        _ => Some(Err(DataflowError::from(EnvelopeError::Flat(
704            "Value not present for message".into(),
705        )))),
706    }
707}
708
709#[cfg(test)]
710mod test {
711    use super::*;
712
713    #[mz_ore::test]
714    fn test_no_default() {
715        let config = StorageMaxInflightBytesConfig {
716            max_inflight_bytes_default: None,
717            max_inflight_bytes_cluster_size_fraction: Some(0.5),
718            disk_only: false,
719        };
720        let memory_limit = Some(1000);
721
722        let backpressure_inflight_bytes_limit =
723            get_backpressure_max_inflight_bytes(&config, &memory_limit);
724
725        assert_eq!(backpressure_inflight_bytes_limit, None)
726    }
727
728    #[mz_ore::test]
729    fn test_no_matching_size() {
730        let config = StorageMaxInflightBytesConfig {
731            max_inflight_bytes_default: Some(10000),
732            max_inflight_bytes_cluster_size_fraction: Some(0.5),
733            disk_only: false,
734        };
735
736        let backpressure_inflight_bytes_limit = get_backpressure_max_inflight_bytes(&config, &None);
737
738        assert_eq!(
739            backpressure_inflight_bytes_limit,
740            config.max_inflight_bytes_default
741        )
742    }
743
744    #[mz_ore::test]
745    fn test_calculated_cluster_limit() {
746        let config = StorageMaxInflightBytesConfig {
747            max_inflight_bytes_default: Some(10000),
748            max_inflight_bytes_cluster_size_fraction: Some(0.5),
749            disk_only: false,
750        };
751        let memory_limit = Some(2000);
752
753        let backpressure_inflight_bytes_limit =
754            get_backpressure_max_inflight_bytes(&config, &memory_limit);
755
756        // the limit should be 50% of 2000 i.e. 1000
757        assert_eq!(backpressure_inflight_bytes_limit, Some(1000));
758    }
759}