mz_storage/storage_state/async_storage_worker.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//! A friendly companion async worker that can be used by a timely storage
11//! worker to do work that requires async.
12//!
13//! CAUTION: This is not meant for high-throughput data processing but for
14//! one-off requests that we need to do every now and then.
15
16use std::collections::BTreeMap;
17use std::fmt::Display;
18use std::sync::Arc;
19use std::thread::Thread;
20use std::time::Duration;
21
22use differential_dataflow::lattice::Lattice;
23use mz_persist_client::Diagnostics;
24use mz_persist_client::cache::PersistClientCache;
25use mz_persist_client::read::ListenEvent;
26use mz_persist_types::Codec64;
27use mz_persist_types::codec_impls::UnitSchema;
28use mz_repr::{GlobalId, Row, TimestampManipulation};
29use mz_storage_types::StorageDiff;
30use mz_storage_types::controller::CollectionMetadata;
31use mz_storage_types::sinks::StorageSinkDesc;
32use mz_storage_types::sources::{
33 GenericSourceConnection, IngestionDescription, KafkaSourceConnection,
34 LoadGeneratorSourceConnection, MySqlSourceConnection, PostgresSourceConnection,
35 SourceConnection, SourceData, SourceEnvelope, SourceTimestamp, SqlServerSourceConnection,
36};
37use timely::order::{PartialOrder, TotalOrder};
38use timely::progress::frontier::MutableAntichain;
39use timely::progress::{Antichain, Timestamp};
40use tokio::sync::mpsc;
41
42use crate::source::types::SourceRender;
43
44/// A worker that can execute commands that come in on a channel and returns
45/// responses on another channel. This is useful in places where we can't
46/// normally run async code, such as the timely main loop.
47#[derive(Debug)]
48pub struct AsyncStorageWorker<T: Timestamp + Lattice + Codec64> {
49 tx: mpsc::UnboundedSender<AsyncStorageWorkerCommand<T>>,
50 rx: crossbeam_channel::Receiver<AsyncStorageWorkerResponse<T>>,
51}
52
53/// Commands for [AsyncStorageWorker].
54#[derive(Debug)]
55pub enum AsyncStorageWorkerCommand<T> {
56 /// Calculate a recent resumption frontier for the ingestion.
57 UpdateIngestionFrontiers(GlobalId, IngestionDescription<CollectionMetadata>),
58
59 /// Calculate a recent resumption frontier for the Sink.
60 UpdateSinkFrontiers(GlobalId, StorageSinkDesc<CollectionMetadata, T>),
61
62 /// This command is used to properly order create and drop of dataflows.
63 /// Currently, this is a no-op in AsyncStorageWorker.
64 ForwardDropDataflow(GlobalId),
65}
66
67/// Responses from [AsyncStorageWorker].
68#[derive(Debug)]
69pub enum AsyncStorageWorkerResponse<T: Timestamp + Lattice + Codec64> {
70 /// An `IngestionDescription` with recent as-of and resume upper frontiers.
71 IngestionFrontiersUpdated {
72 /// ID of the ingestion/source.
73 id: GlobalId,
74 /// The description of the ingestion/source.
75 ingestion_description: IngestionDescription<CollectionMetadata>,
76 /// The frontier beyond which ingested updates should be uncompacted. Inputs to the
77 /// ingestion are guaranteed to be readable at this frontier.
78 as_of: Antichain<T>,
79 /// A frontier in the Materialize time domain with the property that all updates not beyond
80 /// it have already been durably ingested.
81 resume_uppers: BTreeMap<GlobalId, Antichain<T>>,
82 /// A frontier in the source time domain with the property that all updates not beyond it
83 /// have already been durably ingested.
84 source_resume_uppers: BTreeMap<GlobalId, Vec<Row>>,
85 },
86 /// A recent upper of a sink's shard.
87 ExportUpperFetched {
88 /// ID of the sink.
89 id: GlobalId,
90 /// The upper of the sink's shard.
91 upper: Antichain<T>,
92 },
93
94 /// Indicates data flow can be dropped.
95 DropDataflow(GlobalId),
96}
97
98/// Test-only delay of a sink's as-of lookup. Configuring the failpoint as
99/// `sink_frontier_lookup_delay=return(<millis>)` holds each lookup for that long.
100async fn sink_frontier_lookup_failpoint_delay() {
101 let millis = fail::eval("sink_frontier_lookup_delay", |payload| {
102 payload.and_then(|millis| millis.parse::<u64>().ok())
103 });
104 if let Some(millis) = millis.flatten() {
105 tokio::time::sleep(Duration::from_millis(millis)).await;
106 }
107}
108
109async fn reclock_resume_uppers<C, IntoTime>(
110 id: &GlobalId,
111 persist_clients: &PersistClientCache,
112 ingestion_description: &IngestionDescription<CollectionMetadata>,
113 as_of: Antichain<IntoTime>,
114 resume_uppers: &BTreeMap<GlobalId, Antichain<IntoTime>>,
115) -> BTreeMap<GlobalId, Antichain<C::Time>>
116where
117 C: SourceConnection + SourceRender,
118 IntoTime: Timestamp + TotalOrder + Lattice + Codec64 + Display + Sync,
119{
120 let remap_metadata = &ingestion_description.remap_metadata;
121
122 let persist_client = persist_clients
123 .open(remap_metadata.persist_location.clone())
124 .await
125 .expect("location unavailable");
126
127 // We must load enough data in the timestamper to reclock all the requested frontiers
128 let mut remap_updates = vec![];
129 let mut remap_upper = as_of.clone();
130 let mut subscription = None;
131 for upper in resume_uppers.values() {
132 // TODO(petrosagg): this feels icky, we shouldn't have exceptions in frontier reasoning
133 // unless there is a good explanation as to why it is the case. It seems to me that this is
134 // because in various moments in ingestion we mix uppers and sinces and try to derive one
135 // from the other. Investigate if we could explicitly track natively timestamped
136 // since/uppers in the controller.
137 if upper.is_empty() {
138 continue;
139 }
140
141 while PartialOrder::less_than(&remap_upper, upper) {
142 let subscription = match subscription.as_mut() {
143 Some(subscription) => subscription,
144 None => {
145 let read_handle = persist_client
146 .open_leased_reader::<SourceData, (), IntoTime, StorageDiff>(
147 remap_metadata.data_shard.clone(),
148 Arc::new(remap_metadata.relation_desc.clone()),
149 Arc::new(UnitSchema),
150 Diagnostics {
151 shard_name: ingestion_description.remap_collection_id.to_string(),
152 handle_purpose: format!("reclock for {}", id),
153 },
154 false,
155 )
156 .await
157 .expect("shard unavailable");
158
159 let sub = read_handle
160 .subscribe(as_of.clone())
161 .await
162 .expect("always valid to read at since");
163
164 subscription.insert(sub)
165 }
166 };
167 for event in subscription.fetch_next().await {
168 match event {
169 ListenEvent::Updates(updates) => {
170 for ((k, v), t, d) in updates {
171 let row: Row = k.0.expect("invalid binding");
172 let _v: () = v;
173 let from_ts = C::Time::decode_row(&row);
174 remap_updates.push((from_ts, t, d));
175 }
176 }
177 ListenEvent::Progress(f) => remap_upper = f,
178 }
179 }
180 }
181 }
182
183 remap_updates.sort_unstable_by(|a, b| a.1.cmp(&b.1));
184
185 // The conversion of an IntoTime frontier to a FromTime frontier has the property that all
186 // messages that would be reclocked to times beyond the provided `IntoTime` frontier will be
187 // beyond the returned `FromTime` frontier. This can be used to compute a safe starting point
188 // to resume producing an `IntoTime` collection at a particular frontier.
189 let mut source_upper = MutableAntichain::new();
190 let mut source_upper_at_frontier = move |upper: &Antichain<IntoTime>| {
191 if PartialOrder::less_equal(upper, &as_of) {
192 Antichain::from_elem(Timestamp::minimum())
193 } else {
194 let idx = remap_updates.partition_point(|(_, t, _)| !upper.less_equal(t));
195 source_upper.clear();
196 source_upper.update_iter(
197 remap_updates[0..idx]
198 .iter()
199 .map(|(from_time, _, diff)| (from_time.clone(), *diff)),
200 );
201 source_upper.frontier().to_owned()
202 }
203 };
204
205 let mut source_resume_uppers = BTreeMap::new();
206 for (id, upper) in resume_uppers {
207 let source_upper = source_upper_at_frontier(upper);
208 source_resume_uppers.insert(*id, source_upper);
209 }
210 source_resume_uppers
211}
212
213impl<T: Timestamp + TimestampManipulation + Lattice + Codec64 + Display + Sync>
214 AsyncStorageWorker<T>
215{
216 /// Creates a new [`AsyncStorageWorker`].
217 ///
218 /// IMPORTANT: The passed in `thread` is unparked when new responses
219 /// are added the response channel. It is important to not sleep the thread
220 /// that is reading from this via [`try_recv`](Self::try_recv) when
221 /// [`is_empty`](Self::is_empty) has returned `false`.
222 pub fn new(thread: Thread, persist_clients: Arc<PersistClientCache>) -> Self {
223 let (command_tx, mut command_rx) = mpsc::unbounded_channel();
224 let (response_tx, response_rx) = crossbeam_channel::unbounded();
225
226 let response_tx = ActivatingSender::new(response_tx, thread);
227
228 mz_ore::task::spawn(|| "AsyncStorageWorker", async move {
229 while let Some(command) = command_rx.recv().await {
230 match command {
231 AsyncStorageWorkerCommand::UpdateIngestionFrontiers(
232 id,
233 ingestion_description,
234 ) => {
235 let mut resume_uppers = BTreeMap::new();
236
237 for (id, export) in ingestion_description.source_exports.iter() {
238 // Explicit destructuring to force a compile error when the metadata change
239 let CollectionMetadata {
240 persist_location,
241 data_shard,
242 relation_desc,
243 txns_shard,
244 } = &export.storage_metadata;
245 assert_eq!(
246 txns_shard, &None,
247 "source {} unexpectedly using txn-wal",
248 id
249 );
250 let client = persist_clients
251 .open(persist_location.clone())
252 .await
253 .expect("error creating persist client");
254
255 let mut write_handle = client
256 .open_writer::<SourceData, (), T, StorageDiff>(
257 *data_shard,
258 Arc::new(relation_desc.clone()),
259 Arc::new(UnitSchema),
260 Diagnostics {
261 shard_name: id.to_string(),
262 handle_purpose: format!("resumption data {}", id),
263 },
264 )
265 .await
266 .unwrap();
267 let upper = write_handle.fetch_recent_upper().await;
268 let upper = match export.data_config.envelope {
269 // The CdcV2 envelope must re-ingest everything since the Mz frontier does not have a relation to upstream timestamps.
270 // TODO(petrosagg): move this reasoning to the controller
271 SourceEnvelope::CdcV2 if upper.is_empty() => Antichain::new(),
272 SourceEnvelope::CdcV2 => Antichain::from_elem(Timestamp::minimum()),
273 _ => upper.clone(),
274 };
275 resume_uppers.insert(*id, upper);
276 write_handle.expire().await;
277 }
278
279 // Here we update the as-of frontier of the ingestion.
280 //
281 // The as-of frontier controls the frontier with which all inputs of the
282 // ingestion dataflow will be advanced by. It is in our interest to set the
283 // as-of froniter to the largest possible value, which will result in the
284 // maximum amount of consolidation, which in turn results in the minimum
285 // amount of memory required to hydrate.
286 //
287 // For each output `o` and for each input `i` of the ingestion the
288 // controller guarantees that i.since < o.upper except when o.upper is
289 // [T::minimum()]. Therefore the largest as-of for a particular output `o`
290 // is `{ (t - 1).advance_by(i.since) | t in o.upper }`.
291 //
292 // To calculate the global as_of frontier we take the minimum of all those
293 // per-output as-of frontiers.
294 let client = persist_clients
295 .open(
296 ingestion_description
297 .remap_metadata
298 .persist_location
299 .clone(),
300 )
301 .await
302 .expect("error creating persist client");
303 let read_handle = client
304 .open_leased_reader::<SourceData, (), T, StorageDiff>(
305 ingestion_description.remap_metadata.data_shard,
306 Arc::new(
307 ingestion_description.remap_metadata.relation_desc.clone(),
308 ),
309 Arc::new(UnitSchema),
310 Diagnostics {
311 shard_name: ingestion_description
312 .remap_collection_id
313 .to_string(),
314 handle_purpose: format!("resumption data for {}", id),
315 },
316 false,
317 )
318 .await
319 .unwrap();
320 let remap_since = read_handle.since().clone();
321 mz_ore::task::spawn(move || "deferred_expire", async move {
322 tokio::time::sleep(std::time::Duration::from_secs(300)).await;
323 read_handle.expire().await;
324 });
325 let mut as_of = Antichain::new();
326 for upper in resume_uppers.values() {
327 for t in upper.elements() {
328 let mut t_prime = t.step_back().unwrap_or_else(T::minimum);
329 if !remap_since.is_empty() {
330 t_prime.advance_by(remap_since.borrow());
331 as_of.insert(t_prime);
332 }
333 }
334 }
335
336 /// Convenience function to convert `BTreeMap<GlobalId, Antichain<C>>` to
337 /// `BTreeMap<GlobalId, Vec<Row>>`.
338 fn to_vec_row<T: SourceTimestamp>(
339 uppers: BTreeMap<GlobalId, Antichain<T>>,
340 ) -> BTreeMap<GlobalId, Vec<Row>> {
341 uppers
342 .into_iter()
343 .map(|(id, upper)| {
344 (id, upper.into_iter().map(|ts| ts.encode_row()).collect())
345 })
346 .collect()
347 }
348
349 // Create a specialized description to be able to call the generic method
350 let source_resume_uppers = match ingestion_description.desc.connection {
351 GenericSourceConnection::Kafka(_) => {
352 let uppers = reclock_resume_uppers::<KafkaSourceConnection, _>(
353 &id,
354 &persist_clients,
355 &ingestion_description,
356 as_of.clone(),
357 &resume_uppers,
358 )
359 .await;
360 to_vec_row(uppers)
361 }
362 GenericSourceConnection::Postgres(_) => {
363 let uppers = reclock_resume_uppers::<PostgresSourceConnection, _>(
364 &id,
365 &persist_clients,
366 &ingestion_description,
367 as_of.clone(),
368 &resume_uppers,
369 )
370 .await;
371 to_vec_row(uppers)
372 }
373 GenericSourceConnection::MySql(_) => {
374 let uppers = reclock_resume_uppers::<MySqlSourceConnection, _>(
375 &id,
376 &persist_clients,
377 &ingestion_description,
378 as_of.clone(),
379 &resume_uppers,
380 )
381 .await;
382 to_vec_row(uppers)
383 }
384 GenericSourceConnection::SqlServer(_) => {
385 let uppers = reclock_resume_uppers::<SqlServerSourceConnection, _>(
386 &id,
387 &persist_clients,
388 &ingestion_description,
389 as_of.clone(),
390 &resume_uppers,
391 )
392 .await;
393 to_vec_row(uppers)
394 }
395 GenericSourceConnection::LoadGenerator(_) => {
396 let uppers =
397 reclock_resume_uppers::<LoadGeneratorSourceConnection, _>(
398 &id,
399 &persist_clients,
400 &ingestion_description,
401 as_of.clone(),
402 &resume_uppers,
403 )
404 .await;
405 to_vec_row(uppers)
406 }
407 };
408
409 let res = response_tx.send(
410 AsyncStorageWorkerResponse::IngestionFrontiersUpdated {
411 id,
412 ingestion_description,
413 as_of,
414 resume_uppers,
415 source_resume_uppers,
416 },
417 );
418
419 if let Err(_err) = res {
420 // Receiver must have hung up.
421 break;
422 }
423 }
424 AsyncStorageWorkerCommand::UpdateSinkFrontiers(id, description) => {
425 sink_frontier_lookup_failpoint_delay().await;
426
427 let metadata = description.to_storage_metadata.clone();
428 let client = persist_clients
429 .open(metadata.persist_location.clone())
430 .await
431 .expect("error creating persist client");
432
433 let mut write_handle = client
434 .open_writer::<SourceData, (), T, StorageDiff>(
435 metadata.data_shard,
436 Arc::new(metadata.relation_desc),
437 Arc::new(UnitSchema),
438 Diagnostics {
439 shard_name: id.to_string(),
440 handle_purpose: format!("resumption data {}", id),
441 },
442 )
443 .await
444 .unwrap();
445 let upper = write_handle.fetch_recent_upper().await.clone();
446 let res = response_tx
447 .send(AsyncStorageWorkerResponse::ExportUpperFetched { id, upper });
448
449 if let Err(_err) = res {
450 // Receiver must have hung up.
451 break;
452 }
453 }
454 AsyncStorageWorkerCommand::ForwardDropDataflow(id) => {
455 if let Err(_) =
456 response_tx.send(AsyncStorageWorkerResponse::DropDataflow(id))
457 {
458 // Receiver hang up
459 break;
460 }
461 }
462 }
463 }
464 tracing::trace!("shutting down async storage worker task");
465 });
466
467 Self {
468 tx: command_tx,
469 rx: response_rx,
470 }
471 }
472
473 /// Updates the frontiers associated with the provided `IngestionDescription` to recent values.
474 /// Currently this will calculate a fresh as-of for the ingestion and a fresh resumption
475 /// frontier for each of the exports.
476 pub fn update_ingestion_frontiers(
477 &self,
478 id: GlobalId,
479 ingestion: IngestionDescription<CollectionMetadata>,
480 ) {
481 self.send(AsyncStorageWorkerCommand::UpdateIngestionFrontiers(
482 id, ingestion,
483 ))
484 }
485
486 /// Updates the frontiers associated with the provided `StorageSinkDesc` to recent values.
487 /// Currently this will calculate a fresh as-of for the ingestion.
488 pub fn update_sink_frontiers(
489 &self,
490 id: GlobalId,
491 sink: StorageSinkDesc<CollectionMetadata, T>,
492 ) {
493 self.send(AsyncStorageWorkerCommand::UpdateSinkFrontiers(id, sink))
494 }
495
496 /// Enqueue a drop dataflow in the async storage worker channel to ensure proper
497 /// ordering of creating and dropping data flows.
498 pub fn drop_dataflow(&self, id: GlobalId) {
499 self.send(AsyncStorageWorkerCommand::ForwardDropDataflow(id))
500 }
501
502 fn send(&self, cmd: AsyncStorageWorkerCommand<T>) {
503 self.tx
504 .send(cmd)
505 .expect("persist worker exited while its handle was alive")
506 }
507
508 /// Attempts to receive a message from the worker without blocking.
509 ///
510 /// This internally does a `try_recv` on a channel.
511 pub fn try_recv(
512 &self,
513 ) -> Result<AsyncStorageWorkerResponse<T>, crossbeam_channel::TryRecvError> {
514 self.rx.try_recv()
515 }
516
517 /// Returns `true` if there are currently no responses.
518 pub fn is_empty(&self) -> bool {
519 self.rx.is_empty()
520 }
521}
522
523/// Helper that makes sure that we always unpark the target thread when we send a
524/// message.
525struct ActivatingSender<T> {
526 tx: crossbeam_channel::Sender<T>,
527 thread: Thread,
528}
529
530impl<T> ActivatingSender<T> {
531 fn new(tx: crossbeam_channel::Sender<T>, thread: Thread) -> Self {
532 Self { tx, thread }
533 }
534
535 fn send(&self, message: T) -> Result<(), crossbeam_channel::SendError<T>> {
536 let res = self.tx.send(message);
537 self.thread.unpark();
538 res
539 }
540}