mz_storage/source/postgres/snapshot.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//! Renders the table snapshot side of the [`PostgresSourceConnection`] ingestion dataflow.
11//!
12//! # Snapshot reading
13//!
14//! Depending on the resumption LSNs the table reader decides which tables need to be snapshotted
15//! and performs a simple `COPY` query on them in order to get a snapshot. There are a few subtle
16//! points about this operation, described in the following sections.
17//!
18//! ## Consistent LSN point for snapshot transactions
19//!
20//! Given that all our ingestion is based on correctly timestamping updates with the LSN they
21//! happened at it is important that we run the `COPY` query at a specific LSN point that is
22//! relatable with the LSN numbers we receive from the replication stream. Such point does not
23//! necessarily exist for a normal SQL transaction. To achieve this we must force postgres to
24//! produce a consistent point and let us know of the LSN number of that by creating a replication
25//! slot as the first statement in a transaction.
26//!
27//! This is a temporary dummy slot that is only used to put our snapshot transaction on a
28//! consistent LSN point. Unfortunately no lighterweight method exists for doing this. See this
29//! [postgres thread] for more details.
30//!
31//! One might wonder why we don't use the actual real slot to provide us with the snapshot point
32//! which would automatically be at the correct LSN. The answer is that it's possible that we crash
33//! and restart after having already created the slot but before having finished the snapshot. In
34//! that case the restarting process will have lost its opportunity to run queries at the slot's
35//! consistent point as that opportunity only exists in the ephemeral transaction that created the
36//! slot and that is long gone. Additionally there are good reasons of why we'd like to move the
37//! slot creation much earlier, e.g during purification, in which case the slot will always be
38//! pre-created.
39//!
40//! [postgres thread]: https://www.postgresql.org/message-id/flat/CAMN0T-vzzNy6TV1Jvh4xzNQdAvCLBQK_kh6_U7kAXgGU3ZFg-Q%40mail.gmail.com
41//!
42//! ## Reusing the consistent point among all workers
43//!
44//! Creating replication slots is potentially expensive so the code makes is such that all workers
45//! cooperate and reuse one consistent snapshot among them. In order to do so we make use the
46//! "export transaction" feature of postgres. This feature allows one SQL session to create an
47//! identifier for the transaction (a string identifier) it is currently in, which can be used by
48//! other sessions to enter the same "snapshot".
49//!
50//! We accomplish this by picking one worker at random to function as the transaction leader. The
51//! transaction leader is responsible for starting a SQL session, creating a temporary replication
52//! slot in a transaction, exporting the transaction id, and broadcasting the transaction
53//! information to all other workers via a broadcasted feedback edge.
54//!
55//! During this phase the follower workers are simply waiting to hear on the feedback edge,
56//! effectively synchronizing with the leader. Once all workers have received the snapshot
57//! information they can all start to perform their assigned COPY queries.
58//!
59//! The leader and follower steps described above are accomplished by the [`export_snapshot`] and
60//! [`use_snapshot`] functions respectively.
61//!
62//! ## Coordinated transaction COMMIT
63//!
64//! When follower workers are done with snapshotting they commit their transaction, close their
65//! session, and then drop their snapshot feedback capability. When the leader worker is done with
66//! snapshotting it drops its snapshot feedback capability and waits until it observes the
67//! snapshot input advancing to the empty frontier. This allows the leader to COMMIT its
68//! transaction last, which is the transaction that exported the snapshot.
69//!
70//! It's unclear if this is strictly necessary, but having the frontiers made it easy enough that I
71//! added the synchronization.
72//!
73//! ## Snapshot rewinding
74//!
75//! Ingestion dataflows must produce definite data, including the snapshot. What this means
76//! practically is that whenever we deem it necessary to snapshot a table we must do so at the same
77//! LSN. However, the method for running a transaction described above doesn't let us choose the
78//! LSN, it could be an LSN in the future chosen by PostgresSQL while it creates the temporary
79//! replication slot.
80//!
81//! The definition of differential collections states that a collection at some time `t_snapshot`
82//! is defined to be the accumulation of all updates that happen at `t <= t_snapshot`, where `<=`
83//! is the partial order. In this case we are faced with the problem of knowing the state of a
84//! table at `t_snapshot` but actually wanting to know the snapshot at `t_slot <= t_snapshot`.
85//!
86//! From the definition we can see that the snapshot at `t_slot` is related to the snapshot at
87//! `t_snapshot` with the following equations:
88//!
89//!```text
90//! sum(update: t <= t_snapshot) = sum(update: t <= t_slot) + sum(update: t_slot <= t <= t_snapshot)
91//! |
92//! V
93//! sum(update: t <= t_slot) = sum(update: t <= snapshot) - sum(update: t_slot <= t <= t_snapshot)
94//! ```
95//!
96//! Therefore, if we manage to recover the `sum(update: t_slot <= t <= t_snapshot)` term we will be
97//! able to "rewind" the snapshot we obtained at `t_snapshot` to `t_slot` by emitting all updates
98//! that happen between these two points with their diffs negated.
99//!
100//! It turns out that this term is exactly what the main replication slot provides us with and we
101//! can rewind snapshot at arbitrary points! In order to do this the snapshot dataflow emits rewind
102//! requests to the replication reader which informs it that a certain range of updates must be
103//! emitted at LSN 0 (by convention) with their diffs negated. These negated diffs are consolidated
104//! with the diffs taken at `t_snapshot` that were also emitted at LSN 0 (by convention) and we end
105//! up with a TVC that at LSN 0 contains the snapshot at `t_slot`.
106//!
107//! # Snapshot decoding
108//!
109//! The expectation is that tables will most likely be skewed on the number of rows they contain so
110//! while a `COPY` query for any given table runs on a single worker the decoding of the COPY
111//! stream is distributed to all workers.
112//!
113//!
114//! ```text
115//! ╭──────────────────╮
116//! ┏━━━━━━━━━━━━v━┓ │ exported
117//! ┃ table ┃ ╭─────────╮ │ snapshot id
118//! ┃ reader ┠─>─┤broadcast├──╯
119//! ┗━┯━━━━━━━━━━┯━┛ ╰─────────╯
120//! raw│ │
121//! COPY│ │
122//! data│ │
123//! ╭────┴─────╮ │
124//! │distribute│ │
125//! ╰────┬─────╯ │
126//! ┏━━━━┷━━━━┓ │
127//! ┃ COPY ┃ │
128//! ┃ decoder ┃ │
129//! ┗━━━━┯━━━━┛ │
130//! │ snapshot │rewind
131//! │ updates │requests
132//! v v
133//! ```
134
135use std::collections::BTreeMap;
136use std::convert::Infallible;
137use std::pin::pin;
138use std::rc::Rc;
139use std::sync::Arc;
140use std::time::Duration;
141
142use anyhow::bail;
143use differential_dataflow::AsCollection;
144use futures::{StreamExt as _, TryStreamExt};
145use itertools::Itertools;
146use mz_ore::cast::CastFrom;
147use mz_ore::future::InTask;
148use mz_postgres_util::desc::PostgresTableDesc;
149use mz_postgres_util::{Client, Config, PostgresError, simple_query_opt};
150use mz_repr::{Datum, DatumVec, Diff, Row};
151use mz_sql_parser::ast::{Ident, display::AstDisplay};
152use mz_storage_types::connections::ConnectionContext;
153use mz_storage_types::errors::DataflowError;
154use mz_storage_types::parameters::PgSourceSnapshotConfig;
155use mz_storage_types::sources::{MzOffset, PostgresSourceConnection};
156use mz_timely_util::builder_async::{
157 Event as AsyncEvent, OperatorBuilder as AsyncOperatorBuilder, PressOnDropButton,
158};
159use timely::container::CapacityContainerBuilder;
160use timely::dataflow::channels::pact::{Exchange, Pipeline};
161use timely::dataflow::operators::core::Map;
162use timely::dataflow::operators::{
163 Broadcast, CapabilitySet, Concat, ConnectLoop, Feedback, Operator,
164};
165use timely::dataflow::{Scope, Stream};
166use timely::progress::Timestamp;
167use tokio_postgres::error::SqlState;
168use tokio_postgres::types::{Oid, PgLsn};
169use tracing::trace;
170
171use crate::metrics::source::postgres::PgSnapshotMetrics;
172use crate::source::RawSourceCreationConfig;
173use crate::source::postgres::replication::RewindRequest;
174use crate::source::postgres::{
175 DefiniteError, ReplicationError, SourceOutputInfo, TransientError, verify_schema,
176};
177use crate::source::types::{SignaledFuture, SourceMessage, StackedCollection};
178use crate::statistics::SourceStatistics;
179
180/// Renders the snapshot dataflow. See the module documentation for more information.
181pub(crate) fn render<G: Scope<Timestamp = MzOffset>>(
182 mut scope: G,
183 config: RawSourceCreationConfig,
184 connection: PostgresSourceConnection,
185 table_info: BTreeMap<u32, BTreeMap<usize, SourceOutputInfo>>,
186 metrics: PgSnapshotMetrics,
187) -> (
188 StackedCollection<G, (usize, Result<SourceMessage, DataflowError>)>,
189 Stream<G, RewindRequest>,
190 Stream<G, Infallible>,
191 Stream<G, ReplicationError>,
192 PressOnDropButton,
193) {
194 let op_name = format!("TableReader({})", config.id);
195 let mut builder = AsyncOperatorBuilder::new(op_name, scope.clone());
196
197 let (feedback_handle, feedback_data) = scope.feedback(Default::default());
198
199 let (raw_handle, raw_data) = builder.new_output();
200 let (rewinds_handle, rewinds) = builder.new_output::<CapacityContainerBuilder<_>>();
201 // This output is used to signal to the replication operator that the replication slot has been
202 // created. With the current state of execution serialization there isn't a lot of benefit
203 // of splitting the snapshot and replication phases into two operators.
204 // TODO(petrosagg): merge the two operators in one (while still maintaining separation as
205 // functions/modules)
206 let (_, slot_ready) = builder.new_output::<CapacityContainerBuilder<_>>();
207 let (snapshot_handle, snapshot) = builder.new_output::<CapacityContainerBuilder<_>>();
208 let (definite_error_handle, definite_errors) =
209 builder.new_output::<CapacityContainerBuilder<_>>();
210
211 // This operator needs to broadcast data to itself in order to synchronize the transaction
212 // snapshot. However, none of the feedback capabilities result in output messages and for the
213 // feedback edge specifically having a default conncetion would result in a loop.
214 let mut snapshot_input = builder.new_disconnected_input(&feedback_data, Pipeline);
215
216 // The export id must be sent to all workers, so we broadcast the feedback connection
217 snapshot.broadcast().connect_loop(feedback_handle);
218
219 let is_snapshot_leader = config.responsible_for("snapshot_leader");
220
221 // A global view of all outputs that will be snapshot by all workers.
222 let mut all_outputs = vec![];
223 // A filtered table info containing only the tables that this worker should snapshot.
224 let mut worker_table_info = BTreeMap::new();
225 // A collecction of `SourceStatistics` to update for a given Oid. Same info exists in reader_table_info,
226 // but this avoids having to iterate + map each time the statistics are needed.
227 let mut export_statistics = BTreeMap::new();
228 for (table, outputs) in table_info.iter() {
229 for (&output_index, output) in outputs {
230 if *output.resume_upper != [MzOffset::minimum()] {
231 // Already has been snapshotted.
232 continue;
233 }
234 all_outputs.push(output_index);
235 if config.responsible_for(*table) {
236 worker_table_info
237 .entry(*table)
238 .or_insert_with(BTreeMap::new)
239 .insert(output_index, output.clone());
240 }
241 let statistics = config
242 .statistics
243 .get(&output.export_id)
244 .expect("statistics are initialized")
245 .clone();
246 export_statistics.insert((*table, output_index), statistics);
247 }
248 }
249
250 let (button, transient_errors) = builder.build_fallible(move |caps| {
251 let busy_signal = Arc::clone(&config.busy_signal);
252 Box::pin(SignaledFuture::new(busy_signal, async move {
253 let id = config.id;
254 let worker_id = config.worker_id;
255 let [
256 data_cap_set,
257 rewind_cap_set,
258 slot_ready_cap_set,
259 snapshot_cap_set,
260 definite_error_cap_set,
261 ]: &mut [_; 5] = caps.try_into().unwrap();
262
263 trace!(
264 %id,
265 "timely-{worker_id} initializing table reader \
266 with {} tables to snapshot",
267 worker_table_info.len()
268 );
269
270 let connection_config = connection
271 .connection
272 .config(
273 &config.config.connection_context.secrets_reader,
274 &config.config,
275 InTask::Yes,
276 )
277 .await?;
278
279
280 // The snapshot operator is responsible for creating the replication slot(s).
281 // This first slot is the permanent slot that will be used for reading the replication
282 // stream. A temporary slot is created further on to capture table snapshots.
283 let replication_client = if is_snapshot_leader {
284 let client = connection_config
285 .connect_replication(&config.config.connection_context.ssh_tunnel_manager)
286 .await?;
287 let main_slot = &connection.publication_details.slot;
288
289 tracing::info!(%id, "ensuring replication slot {main_slot} exists");
290 super::ensure_replication_slot(&client, main_slot).await?;
291 Some(client)
292 } else {
293 None
294 };
295 *slot_ready_cap_set = CapabilitySet::new();
296
297 // Nothing needs to be snapshot.
298 if all_outputs.is_empty() {
299 trace!(%id, "no exports to snapshot");
300 // Note we do not emit a `ProgressStatisticsUpdate::Snapshot` update here,
301 // as we do not want to attempt to override the current value with 0. We
302 // just leave it null.
303 return Ok(());
304 }
305
306 // A worker *must* emit a count even if not responsible for snapshotting a table
307 // as statistic summarization will return null if any worker hasn't set a value.
308 // This will also reset snapshot stats for any exports not snapshotting.
309 // If no workers need to snapshot, then avoid emitting these as they will clear
310 // previous stats.
311 for statistics in config.statistics.values() {
312 statistics.set_snapshot_records_known(0);
313 statistics.set_snapshot_records_staged(0);
314 }
315
316 // replication client is only set if this worker is the snapshot leader
317 let client = match replication_client {
318 Some(client) => {
319 let tmp_slot = format!("mzsnapshot_{}", uuid::Uuid::new_v4()).replace('-', "");
320 let snapshot_info = export_snapshot(&client, &tmp_slot, true).await?;
321 trace!(
322 %id,
323 "timely-{worker_id} exporting snapshot info {snapshot_info:?}");
324 snapshot_handle.give(&snapshot_cap_set[0], snapshot_info);
325
326 client
327 }
328 None => {
329 // Only the snapshot leader needs a replication connection.
330 let task_name = format!("timely-{worker_id} PG snapshotter");
331 connection_config
332 .connect(
333 &task_name,
334 &config.config.connection_context.ssh_tunnel_manager,
335 )
336 .await?
337 }
338 };
339
340 // Configure statement_timeout based on param. We want to be able to
341 // override the server value here in case it's set too low,
342 // respective to the size of the data we need to copy.
343 set_statement_timeout(
344 &client,
345 config
346 .config
347 .parameters
348 .pg_source_snapshot_statement_timeout,
349 )
350 .await?;
351
352 let (snapshot, snapshot_lsn) = loop {
353 match snapshot_input.next().await {
354 Some(AsyncEvent::Data(_, mut data)) => {
355 break data.pop().expect("snapshot sent above")
356 }
357 Some(AsyncEvent::Progress(_)) => continue,
358 None => panic!(
359 "feedback closed \
360 before sending snapshot info"
361 ),
362 }
363 };
364 // Snapshot leader is already in identified transaction but all other workers need to enter it.
365 if !is_snapshot_leader {
366 trace!(%id, "timely-{worker_id} using snapshot id {snapshot:?}");
367 use_snapshot(&client, &snapshot).await?;
368 }
369
370
371 let upstream_info = {
372 let table_oids = worker_table_info.keys().copied().collect::<Vec<_>>();
373 // As part of retrieving the schema info, RLS policies are checked to ensure the
374 // snapshot can successfully read the tables. RLS policy errors are treated as
375 // transient, as the customer can simply add the BYPASSRLS to the PG account
376 // used by MZ.
377 match retrieve_schema_info(
378 &connection_config,
379 &config.config.connection_context,
380 &connection.publication,
381 &table_oids)
382 .await
383 {
384 // If the replication stream cannot be obtained in a definite way there is
385 // nothing else to do. These errors are not retractable.
386 Err(PostgresError::PublicationMissing(publication)) => {
387 let err = DefiniteError::PublicationDropped(publication);
388 for (oid, outputs) in worker_table_info.iter() {
389 // Produce a definite error here and then exit to ensure
390 // a missing publication doesn't generate a transient
391 // error and restart this dataflow indefinitely.
392 //
393 // We pick `u64::MAX` as the LSN which will (in
394 // practice) never conflict any previously revealed
395 // portions of the TVC.
396 for output_index in outputs.keys() {
397 let update = (
398 (*oid, *output_index, Err(err.clone().into())),
399 MzOffset::from(u64::MAX),
400 Diff::ONE,
401 );
402 raw_handle.give_fueled(&data_cap_set[0], update).await;
403 }
404 }
405
406 definite_error_handle.give(
407 &definite_error_cap_set[0],
408 ReplicationError::Definite(Rc::new(err)),
409 );
410 return Ok(());
411 },
412 Err(e) => Err(TransientError::from(e))?,
413 Ok(i) => i,
414 }
415 };
416
417 report_snapshot_size(&client, &worker_table_info, metrics, &config, &export_statistics).await?;
418
419 for (&oid, outputs) in worker_table_info.iter() {
420 for (&output_index, info) in outputs.iter() {
421 if let Err(err) = verify_schema(oid, info, &upstream_info) {
422 raw_handle
423 .give_fueled(
424 &data_cap_set[0],
425 (
426 (oid, output_index, Err(err.into())),
427 MzOffset::minimum(),
428 Diff::ONE,
429 ),
430 )
431 .await;
432 continue;
433 }
434
435 trace!(
436 %id,
437 "timely-{worker_id} snapshotting table {:?}({oid}) @ {snapshot_lsn}",
438 info.desc.name
439 );
440
441 // To handle quoted/keyword names, we can use `Ident`'s AST printing, which
442 // emulate's PG's rules for name formatting.
443 let namespace = Ident::new_unchecked(&info.desc.namespace).to_ast_string_stable();
444 let table = Ident::new_unchecked(&info.desc.name).to_ast_string_stable();
445 let column_list = info
446 .desc
447 .columns
448 .iter()
449 .map(|c| Ident::new_unchecked(&c.name).to_ast_string_stable())
450 .join(",");
451 let query = format!("COPY {namespace}.{table} ({column_list}) \
452 TO STDOUT (FORMAT TEXT, DELIMITER '\t')");
453 let mut stream = pin!(client.copy_out_simple(&query).await?);
454
455 let mut snapshot_staged = 0;
456 let mut update = ((oid, output_index, Ok(vec![])), MzOffset::minimum(), Diff::ONE);
457 while let Some(bytes) = stream.try_next().await? {
458 let data = update.0 .2.as_mut().unwrap();
459 data.clear();
460 data.extend_from_slice(&bytes);
461 raw_handle.give_fueled(&data_cap_set[0], &update).await;
462 snapshot_staged += 1;
463 if snapshot_staged % 1000 == 0 {
464 export_statistics[&(oid, output_index)].set_snapshot_records_staged(snapshot_staged);
465 }
466 }
467 // final update for snapshot_staged, using the staged values as the total is an estimate
468 export_statistics[&(oid, output_index)].set_snapshot_records_staged(snapshot_staged);
469 export_statistics[&(oid, output_index)].set_snapshot_records_known(snapshot_staged);
470 }
471 }
472
473 // We are done with the snapshot so now we will emit rewind requests. It is important
474 // that this happens after the snapshot has finished because this is what unblocks the
475 // replication operator and we want this to happen serially. It might seem like a good
476 // idea to read the replication stream concurrently with the snapshot but it actually
477 // leads to a lot of data being staged for the future, which needlesly consumed memory
478 // in the cluster.
479 for output in worker_table_info.values() {
480 for (output_index, info) in output {
481 trace!(%id, "timely-{worker_id} producing rewind request for table {} output {output_index}", info.desc.name);
482 let req = RewindRequest { output_index: *output_index, snapshot_lsn };
483 rewinds_handle.give(&rewind_cap_set[0], req);
484 }
485 }
486 *rewind_cap_set = CapabilitySet::new();
487
488 // Failure scenario after we have produced the snapshot, but before a successful COMMIT
489 fail::fail_point!("pg_snapshot_failure", |_| Err(
490 TransientError::SyntheticError
491 ));
492
493 // The exporting worker should wait for all the other workers to commit before dropping
494 // its client since this is what holds the exported transaction alive.
495 if is_snapshot_leader {
496 trace!(%id, "timely-{worker_id} waiting for all workers to finish");
497 *snapshot_cap_set = CapabilitySet::new();
498 while snapshot_input.next().await.is_some() {}
499 trace!(%id, "timely-{worker_id} (leader) comitting COPY transaction");
500 client.simple_query("COMMIT").await?;
501 } else {
502 trace!(%id, "timely-{worker_id} comitting COPY transaction");
503 client.simple_query("COMMIT").await?;
504 *snapshot_cap_set = CapabilitySet::new();
505 }
506 drop(client);
507 Ok(())
508 }))
509 });
510
511 // We now decode the COPY protocol and apply the cast expressions
512 let mut text_row = Row::default();
513 let mut final_row = Row::default();
514 let mut datum_vec = DatumVec::new();
515 let mut next_worker = (0..u64::cast_from(scope.peers()))
516 // Round robin on 1000-records basis to avoid creating tiny containers when there are a
517 // small number of updates and a large number of workers.
518 .flat_map(|w| std::iter::repeat_n(w, 1000))
519 .cycle();
520 let round_robin = Exchange::new(move |_| next_worker.next().unwrap());
521 let snapshot_updates = raw_data
522 .map::<Vec<_>, _, _>(Clone::clone)
523 .unary(round_robin, "PgCastSnapshotRows", |_, _| {
524 move |input, output| {
525 input.for_each_time(|time, data| {
526 let mut session = output.session(&time);
527 for ((oid, output_index, event), time, diff) in
528 data.flat_map(|data| data.drain(..))
529 {
530 let output = &table_info
531 .get(&oid)
532 .and_then(|outputs| outputs.get(&output_index))
533 .expect("table_info contains all outputs");
534
535 let event = event
536 .as_ref()
537 .map_err(|e: &DataflowError| e.clone())
538 .and_then(|bytes| {
539 decode_copy_row(bytes, output.casts.len(), &mut text_row)?;
540 let datums = datum_vec.borrow_with(&text_row);
541 super::cast_row(&output.casts, &datums, &mut final_row)?;
542 Ok(SourceMessage {
543 key: Row::default(),
544 value: final_row.clone(),
545 metadata: Row::default(),
546 })
547 });
548
549 session.give(((output_index, event), time, diff));
550 }
551 });
552 }
553 })
554 .as_collection();
555
556 let errors = definite_errors.concat(&transient_errors.map(ReplicationError::from));
557
558 (
559 snapshot_updates,
560 rewinds,
561 slot_ready,
562 errors,
563 button.press_on_drop(),
564 )
565}
566
567/// Starts a read-only transaction on the SQL session of `client` at a consistent LSN point by
568/// creating a replication slot. Returns a snapshot identifier that can be imported in
569/// other SQL session and the LSN of the consistent point.
570async fn export_snapshot(
571 client: &Client,
572 slot: &str,
573 temporary: bool,
574) -> Result<(String, MzOffset), TransientError> {
575 match export_snapshot_inner(client, slot, temporary).await {
576 Ok(ok) => Ok(ok),
577 Err(err) => {
578 // We don't want to leave the client inside a failed tx
579 client.simple_query("ROLLBACK;").await?;
580 Err(err)
581 }
582 }
583}
584
585async fn export_snapshot_inner(
586 client: &Client,
587 slot: &str,
588 temporary: bool,
589) -> Result<(String, MzOffset), TransientError> {
590 client
591 .simple_query("BEGIN READ ONLY ISOLATION LEVEL REPEATABLE READ;")
592 .await?;
593
594 // Note: Using unchecked here is okay because we're using it in a SQL query.
595 let slot = Ident::new_unchecked(slot).to_ast_string_simple();
596 let temporary_str = if temporary { " TEMPORARY" } else { "" };
597 let query =
598 format!("CREATE_REPLICATION_SLOT {slot}{temporary_str} LOGICAL \"pgoutput\" USE_SNAPSHOT");
599 let row = match simple_query_opt(client, &query).await {
600 Ok(row) => Ok(row.unwrap()),
601 Err(PostgresError::Postgres(err)) if err.code() == Some(&SqlState::DUPLICATE_OBJECT) => {
602 return Err(TransientError::ReplicationSlotAlreadyExists);
603 }
604 Err(err) => Err(err),
605 }?;
606
607 // When creating a replication slot postgres returns the LSN of its consistent point, which is
608 // the LSN that must be passed to `START_REPLICATION` to cleanly transition from the snapshot
609 // phase to the replication phase. `START_REPLICATION` includes all transactions that commit at
610 // LSNs *greater than or equal* to the passed LSN. Therefore the snapshot phase must happen at
611 // the greatest LSN that is not beyond the consistent point. That LSN is `consistent_point - 1`
612 let consistent_point: PgLsn = row.get("consistent_point").unwrap().parse().unwrap();
613 let consistent_point = u64::from(consistent_point)
614 .checked_sub(1)
615 .expect("consistent point is always non-zero");
616
617 let row = simple_query_opt(client, "SELECT pg_export_snapshot();")
618 .await?
619 .unwrap();
620 let snapshot = row.get("pg_export_snapshot").unwrap().to_owned();
621
622 Ok((snapshot, MzOffset::from(consistent_point)))
623}
624
625/// Starts a read-only transaction on the SQL session of `client` at a the consistent LSN point of
626/// `snapshot`.
627async fn use_snapshot(client: &Client, snapshot: &str) -> Result<(), TransientError> {
628 client
629 .simple_query("BEGIN READ ONLY ISOLATION LEVEL REPEATABLE READ;")
630 .await?;
631 let query = format!("SET TRANSACTION SNAPSHOT '{snapshot}';");
632 client.simple_query(&query).await?;
633 Ok(())
634}
635
636async fn set_statement_timeout(client: &Client, timeout: Duration) -> Result<(), TransientError> {
637 // Value is known to accept milliseconds w/o units.
638 // https://www.postgresql.org/docs/current/runtime-config-client.html
639 client
640 .simple_query(&format!("SET statement_timeout = {}", timeout.as_millis()))
641 .await?;
642 Ok(())
643}
644
645/// Decodes a row of `col_len` columns obtained from a text encoded COPY query into `row`.
646fn decode_copy_row(data: &[u8], col_len: usize, row: &mut Row) -> Result<(), DefiniteError> {
647 let mut packer = row.packer();
648 let row_parser = mz_pgcopy::CopyTextFormatParser::new(data, b'\t', "\\N");
649 let mut column_iter = row_parser.iter_raw_truncating(col_len);
650 for _ in 0..col_len {
651 let value = match column_iter.next() {
652 Some(Ok(value)) => value,
653 Some(Err(_)) => return Err(DefiniteError::InvalidCopyInput),
654 None => return Err(DefiniteError::MissingColumn),
655 };
656 let datum = value.map(super::decode_utf8_text).transpose()?;
657 packer.push(datum.unwrap_or(Datum::Null));
658 }
659 Ok(())
660}
661
662/// Record the sizes of the tables being snapshotted in `PgSnapshotMetrics` and emit snapshot statistics for each export.
663async fn report_snapshot_size(
664 client: &Client,
665 worker_table_info: &BTreeMap<u32, BTreeMap<usize, SourceOutputInfo>>,
666 metrics: PgSnapshotMetrics,
667 config: &RawSourceCreationConfig,
668 export_statistics: &BTreeMap<(u32, usize), SourceStatistics>,
669) -> Result<(), anyhow::Error> {
670 // TODO(guswynn): delete unused configs
671 let snapshot_config = config.config.parameters.pg_snapshot_config;
672
673 for (&oid, outputs) in worker_table_info {
674 // Use the first output's desc to make the table name since it is the same for all outputs
675 let Some((_, info)) = outputs.first_key_value() else {
676 continue;
677 };
678 let table = format!(
679 "{}.{}",
680 Ident::new_unchecked(info.desc.namespace.clone()).to_ast_string_simple(),
681 Ident::new_unchecked(info.desc.name.clone()).to_ast_string_simple()
682 );
683 let stats =
684 collect_table_statistics(client, snapshot_config, &table, info.desc.oid).await?;
685 metrics.record_table_count_latency(table, stats.count_latency);
686 for &output_index in outputs.keys() {
687 export_statistics[&(oid, output_index)].set_snapshot_records_known(stats.count);
688 export_statistics[&(oid, output_index)].set_snapshot_records_staged(0);
689 }
690 }
691 Ok(())
692}
693
694#[derive(Default)]
695struct TableStatistics {
696 count: u64,
697 count_latency: f64,
698}
699
700async fn collect_table_statistics(
701 client: &Client,
702 config: PgSourceSnapshotConfig,
703 table: &str,
704 oid: u32,
705) -> Result<TableStatistics, anyhow::Error> {
706 use mz_ore::metrics::MetricsFutureExt;
707 let mut stats = TableStatistics::default();
708
709 let estimate_row = simple_query_opt(
710 client,
711 &format!("SELECT reltuples::bigint AS estimate_count FROM pg_class WHERE oid = '{oid}'"),
712 )
713 .wall_time()
714 .set_at(&mut stats.count_latency)
715 .await?;
716 stats.count = match estimate_row {
717 Some(row) => row.get("estimate_count").unwrap().parse().unwrap_or(0),
718 None => bail!("failed to get estimate count for {table}"),
719 };
720
721 // If the estimate is low enough we can attempt to get an exact count. Note that not yet
722 // vacuumed tables will report zero rows here and there is a possibility that they are very
723 // large. We accept this risk and we offer the feature flag as an escape hatch if it becomes
724 // problematic.
725 if config.collect_strict_count && stats.count < 1_000_000 {
726 let count_row = simple_query_opt(client, &format!("SELECT count(*) as count from {table}"))
727 .wall_time()
728 .set_at(&mut stats.count_latency)
729 .await?;
730 stats.count = match count_row {
731 Some(row) => row.get("count").unwrap().parse().unwrap(),
732 None => bail!("failed to get count for {table}"),
733 }
734 }
735
736 Ok(stats)
737}
738
739/// Validates that there are no blocking RLS polcicies on the tables and retrieves table schemas
740/// for the given publication.
741async fn retrieve_schema_info(
742 connection_config: &Config,
743 connection_context: &ConnectionContext,
744 publication: &str,
745 table_oids: &[Oid],
746) -> Result<BTreeMap<u32, PostgresTableDesc>, PostgresError> {
747 let schema_client = connection_config
748 .connect(
749 "snapshot schema info",
750 &connection_context.ssh_tunnel_manager,
751 )
752 .await?;
753 mz_postgres_util::validate_no_rls_policies(&schema_client, table_oids).await?;
754 mz_postgres_util::publication_info(&schema_client, publication, Some(table_oids)).await
755}