mz_compute/render/
sinks.rs1use std::any::Any;
13use std::collections::{BTreeMap, BTreeSet};
14use std::rc::Rc;
15
16use differential_dataflow::VecCollection;
17use mz_compute_types::plan::scalar::LirScalarExpr;
18use mz_compute_types::sinks::{ComputeSinkConnection, ComputeSinkDesc};
19use mz_expr::{EvalError, MapFilterProject, permutation_for_arrangement};
20use mz_ore::soft_assert_or_log;
21use mz_ore::str::StrExt;
22use mz_ore::vec::PartialOrdVecExt;
23use mz_repr::{Diff, GlobalId, Row};
24use mz_storage_types::controller::CollectionMetadata;
25use mz_timely_util::operator::CollectionExt;
26use mz_timely_util::probe::Handle;
27use timely::container::CapacityContainerBuilder;
28use timely::dataflow::Scope;
29use timely::progress::Antichain;
30
31use crate::compute_state::SinkToken;
32use crate::logging::compute::LogDataflowErrors;
33use crate::render::context::Context;
34use crate::render::errors::DataflowErrorSer;
35use crate::render::{RenderTimestamp, StartSignal};
36
37impl<'g, T: RenderTimestamp> Context<'g, T> {
38 pub(crate) fn export_sink(
40 &self,
41 compute_state: &mut crate::compute_state::ComputeState,
42 tokens: &BTreeMap<GlobalId, Rc<dyn Any>>,
43 dependency_ids: BTreeSet<GlobalId>,
44 sink_id: GlobalId,
45 sink: &ComputeSinkDesc<CollectionMetadata>,
46 start_signal: StartSignal,
47 output_probe: &Handle<mz_repr::Timestamp>,
48 outer_scope: Scope<'g, mz_repr::Timestamp>,
49 ) {
50 soft_assert_or_log!(
51 sink.non_null_assertions.is_strictly_sorted(),
52 "non-null assertions not sorted"
53 );
54
55 let mut needed_tokens = Vec::new();
57 for dep_id in dependency_ids {
58 if let Some(token) = tokens.get(&dep_id) {
59 needed_tokens.push(Rc::clone(token))
60 }
61 }
62
63 let bundle = self
68 .lookup_id(mz_expr::Id::Global(sink.from))
69 .expect("Sink source collection not loaded");
70 let (ok_collection, mut err_collection) = if let Some(collection) = &bundle.collection {
71 collection.clone()
72 } else {
73 let (key, _arrangement) = bundle
74 .arranged
75 .iter()
76 .next()
77 .expect("Invariant violated: at least one collection must be present.");
78 let unthinned_arity = sink.from_desc.arity();
79 let (permutation, thinning) = permutation_for_arrangement(key, unthinned_arity);
80 let mut mfp = MapFilterProject::<LirScalarExpr>::new(unthinned_arity);
81 mfp.permute_fn(|c| permutation[c], thinning.len() + key.len());
82 let mfp_plan = mfp.into_plan().expect("MFP planning failed");
83 bundle.as_collection_core(
84 mfp_plan,
85 Some((key.clone(), None)),
86 self.until.clone(),
87 &self.config_set,
88 )
89 };
90
91 if let Some(logger) = compute_state.compute_logger.clone() {
93 err_collection = err_collection.log_dataflow_errors(logger, sink_id);
94 }
95
96 let mut ok_collection = ok_collection.leave(outer_scope);
97 let mut err_collection = err_collection.leave(outer_scope);
98
99 if let Some(&expiration) = self.dataflow_expiration.as_option() {
102 ok_collection = ok_collection
103 .expire_collection_at(&format!("{}_export_sink_oks", self.debug_name), expiration);
104 err_collection = err_collection
105 .expire_collection_at(&format!("{}_export_sink_errs", self.debug_name), expiration);
106 }
107
108 let non_null_assertions = sink.non_null_assertions.clone();
109 let from_desc = sink.from_desc.clone();
110 if !non_null_assertions.is_empty() {
111 let name = format!("NullAssertions({sink_id:?})");
112 type CB<C> = CapacityContainerBuilder<C>;
113 let (oks, null_errs) =
114 ok_collection.map_fallible::<CB<_>, CB<_>, _, _, _>(&name, move |row| {
115 let mut idx = 0;
116 let mut iter = row.iter();
117 for &i in &non_null_assertions {
118 let skip = i - idx;
119 let datum = iter.nth(skip).unwrap();
120 idx += skip + 1;
121 if datum.is_null() {
122 return Err(DataflowErrorSer::from(EvalError::MustNotBeNull(
123 format!("column {}", from_desc.get_name(i).quoted()).into(),
124 )));
125 }
126 }
127 Ok(row)
128 });
129 ok_collection = oks;
130 err_collection = err_collection.concat(null_errs);
131 }
132
133 let region_name = match sink.connection {
134 ComputeSinkConnection::Subscribe(_) => format!("SubscribeSink({:?})", sink_id),
135 ComputeSinkConnection::MaterializedView(_) => {
136 format!("MaterializedViewSink({:?})", sink_id)
137 }
138 ComputeSinkConnection::CopyToS3Oneshot(_) => {
139 format!("CopyToS3OneshotSink({:?})", sink_id)
140 }
141 };
142 outer_scope.clone().region_named(®ion_name, |inner| {
143 let sink_render = get_sink_render_for(&sink.connection);
144
145 let sink_token = sink_render.render_sink(
146 compute_state,
147 sink,
148 sink_id,
149 self.as_of_frontier.clone(),
150 start_signal,
151 ok_collection.enter_region(inner),
152 err_collection.enter_region(inner),
153 output_probe,
154 );
155
156 if let Some(sink_token) = sink_token {
157 needed_tokens.push(sink_token);
158 }
159
160 let collection = compute_state.expect_collection_mut(sink_id);
161 collection.sink_token = Some(SinkToken::new(Box::new(needed_tokens)));
162 });
163 }
164}
165
166pub(crate) trait SinkRender<'scope> {
168 fn render_sink(
169 &self,
170 compute_state: &mut crate::compute_state::ComputeState,
171 sink: &ComputeSinkDesc<CollectionMetadata>,
172 sink_id: GlobalId,
173 as_of: Antichain<mz_repr::Timestamp>,
174 start_signal: StartSignal,
175 sinked_collection: VecCollection<'scope, mz_repr::Timestamp, Row, Diff>,
176 err_collection: VecCollection<'scope, mz_repr::Timestamp, DataflowErrorSer, Diff>,
177 output_probe: &Handle<mz_repr::Timestamp>,
178 ) -> Option<Rc<dyn Any>>;
179}
180
181fn get_sink_render_for<'scope>(
182 connection: &ComputeSinkConnection<CollectionMetadata>,
183) -> Box<dyn SinkRender<'scope>> {
184 match connection {
185 ComputeSinkConnection::Subscribe(connection) => Box::new(connection.clone()),
186 ComputeSinkConnection::MaterializedView(connection) => Box::new(connection.clone()),
187 ComputeSinkConnection::CopyToS3Oneshot(connection) => Box::new(connection.clone()),
188 }
189}