mz_storage/source/postgres/
replication.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 logical replication side of the [`PostgresSourceConnection`] ingestion dataflow.
11//!
12//! ```text
13//!              o
14//!              │rewind
15//!              │requests
16//!          ╭───┴────╮
17//!          │exchange│ (collect all requests to one worker)
18//!          ╰───┬────╯
19//!           ┏━━v━━━━━━━━━━┓
20//!           ┃ replication ┃ (single worker)
21//!           ┃   reader    ┃
22//!           ┗━┯━━━━━━━━┯━━┛
23//!             │raw     │
24//!             │data    │
25//!        ╭────┴─────╮  │
26//!        │distribute│  │ (distribute to all workers)
27//!        ╰────┬─────╯  │
28//! ┏━━━━━━━━━━━┷━┓      │
29//! ┃ replication ┃      │ (parallel decode)
30//! ┃   decoder   ┃      │
31//! ┗━━━━━┯━━━━━━━┛      │
32//!       │ replication  │ progress
33//!       │ updates      │ output
34//!       v              v
35//! ```
36//!
37//! # Progress tracking
38//!
39//! In order to avoid causing excessive resource usage in the upstream server it's important to
40//! track the LSN that we have successfully committed to persist and communicate that back to
41//! PostgreSQL. Under normal operation this gauge of progress is provided by the presence of
42//! transactions themselves. Since at a given LSN offset there can be only a single message, when a
43//! transaction is received and processed we can infer that we have seen all the messages that are
44//! not beyond `commit_lsn + 1`.
45//!
46//! Things are a bit more complicated in the absence of transactions though because even though we
47//! don't receive any the server might very well be generating WAL records. This can happen if
48//! there is a separate logical database performing writes (which is the case for RDS databases),
49//! or, in servers running PostgreSQL version 15 or greater, the logical replication process
50//! includes an optimization that omits empty transactions, which can happen if you're only
51//! replicating a subset of the tables and there writes going to the other ones.
52//!
53//! If we fail to detect this situation and don't send LSN feedback in a timely manner the server
54//! will be forced to keep around WAL data that can eventually lead to disk space exhaustion.
55//!
56//! In the absence of transactions the only available piece of information in the replication
57//! stream are keepalive messages. Keepalive messages are documented[1] to contain the current end
58//! of WAL on the server. That is a useless number when it comes to progress tracking because there
59//! might be pending messages at LSNs between the last received commit_lsn and the current end of
60//! WAL.
61//!
62//! Fortunately for us, the documentation for PrimaryKeepalive messages is wrong and it actually
63//! contains the last *sent* LSN[2]. Here sent doesn't necessarily mean sent over the wire, but
64//! sent to the upstream process that is handling producing the logical stream. Therefore, if we
65//! receive a keepalive with a particular LSN we can be certain that there are no other replication
66//! messages at previous LSNs, because they would have been already generated and received. We
67//! therefore connect the keepalive messages directly to our capability.
68//!
69//! [1]: https://www.postgresql.org/docs/15/protocol-replication.html#PROTOCOL-REPLICATION-START-REPLICATION
70//! [2]: https://www.postgresql.org/message-id/CAFPTHDZS9O9WG02EfayBd6oONzK%2BqfUxS6AbVLJ7W%2BKECza2gg%40mail.gmail.com
71
72use std::collections::BTreeMap;
73use std::convert::Infallible;
74use std::pin::pin;
75use std::rc::Rc;
76use std::str::FromStr;
77use std::sync::Arc;
78use std::sync::LazyLock;
79use std::time::Instant;
80use std::time::{Duration, SystemTime, UNIX_EPOCH};
81
82use differential_dataflow::AsCollection;
83use futures::{FutureExt, Stream as AsyncStream, StreamExt, TryStreamExt};
84use mz_ore::cast::CastFrom;
85use mz_ore::future::InTask;
86use mz_postgres_util::PostgresError;
87use mz_postgres_util::{Client, simple_query_opt};
88use mz_repr::{Datum, DatumVec, Diff, Row};
89use mz_sql_parser::ast::{Ident, display::AstDisplay};
90use mz_storage_types::dyncfgs::{PG_OFFSET_KNOWN_INTERVAL, PG_SCHEMA_VALIDATION_INTERVAL};
91use mz_storage_types::errors::DataflowError;
92use mz_storage_types::sources::{MzOffset, PostgresSourceConnection};
93use mz_timely_util::builder_async::{
94    AsyncOutputHandle, Event as AsyncEvent, OperatorBuilder as AsyncOperatorBuilder,
95    PressOnDropButton,
96};
97use postgres_replication::LogicalReplicationStream;
98use postgres_replication::protocol::{LogicalReplicationMessage, ReplicationMessage, TupleData};
99use serde::{Deserialize, Serialize};
100use timely::container::CapacityContainerBuilder;
101use timely::dataflow::channels::pact::{Exchange, Pipeline};
102use timely::dataflow::operators::Capability;
103use timely::dataflow::operators::Concat;
104use timely::dataflow::operators::Operator;
105use timely::dataflow::operators::core::Map;
106use timely::dataflow::{Scope, Stream};
107use timely::progress::Antichain;
108use tokio::sync::{mpsc, watch};
109use tokio_postgres::error::SqlState;
110use tokio_postgres::types::PgLsn;
111use tracing::{error, trace};
112
113use crate::metrics::source::postgres::PgSourceMetrics;
114use crate::source::RawSourceCreationConfig;
115use crate::source::postgres::verify_schema;
116use crate::source::postgres::{DefiniteError, ReplicationError, SourceOutputInfo, TransientError};
117use crate::source::probe;
118use crate::source::types::{Probe, SignaledFuture, SourceMessage, StackedCollection};
119
120/// Postgres epoch is 2000-01-01T00:00:00Z
121static PG_EPOCH: LazyLock<SystemTime> =
122    LazyLock::new(|| UNIX_EPOCH + Duration::from_secs(946_684_800));
123
124// A request to rewind a snapshot taken at `snapshot_lsn` to the initial LSN of the replication
125// slot. This is accomplished by emitting `(data, 0, -diff)` for all updates `(data, lsn, diff)`
126// whose `lsn <= snapshot_lsn`. By convention the snapshot is always emitted at LSN 0.
127#[derive(Debug, Clone, Serialize, Deserialize)]
128pub(crate) struct RewindRequest {
129    /// The output index that should be rewound.
130    pub(crate) output_index: usize,
131    /// The LSN that the snapshot was taken at.
132    pub(crate) snapshot_lsn: MzOffset,
133}
134
135/// Renders the replication dataflow. See the module documentation for more information.
136pub(crate) fn render<G: Scope<Timestamp = MzOffset>>(
137    scope: G,
138    config: RawSourceCreationConfig,
139    connection: PostgresSourceConnection,
140    table_info: BTreeMap<u32, BTreeMap<usize, SourceOutputInfo>>,
141    rewind_stream: &Stream<G, RewindRequest>,
142    slot_ready_stream: &Stream<G, Infallible>,
143    committed_uppers: impl futures::Stream<Item = Antichain<MzOffset>> + 'static,
144    metrics: PgSourceMetrics,
145) -> (
146    StackedCollection<G, (usize, Result<SourceMessage, DataflowError>)>,
147    Stream<G, Infallible>,
148    Option<Stream<G, Probe<MzOffset>>>,
149    Stream<G, ReplicationError>,
150    PressOnDropButton,
151) {
152    let op_name = format!("ReplicationReader({})", config.id);
153    let mut builder = AsyncOperatorBuilder::new(op_name, scope.clone());
154
155    let slot_reader = u64::cast_from(config.responsible_worker("slot"));
156    let (data_output, data_stream) = builder.new_output();
157    let (_upper_output, upper_stream) = builder.new_output::<CapacityContainerBuilder<_>>();
158    let (definite_error_handle, definite_errors) =
159        builder.new_output::<CapacityContainerBuilder<_>>();
160    let (probe_output, probe_stream) = builder.new_output::<CapacityContainerBuilder<_>>();
161
162    let mut rewind_input =
163        builder.new_disconnected_input(rewind_stream, Exchange::new(move |_| slot_reader));
164    let mut slot_ready_input = builder.new_disconnected_input(slot_ready_stream, Pipeline);
165    let output_uppers = table_info
166        .iter()
167        .flat_map(|(_, outputs)| outputs.values().map(|o| o.resume_upper.clone()))
168        .collect::<Vec<_>>();
169    metrics.tables.set(u64::cast_from(output_uppers.len()));
170
171    let reader_table_info = table_info.clone();
172    let (button, transient_errors) = builder.build_fallible(move |caps| {
173        let mut table_info = reader_table_info;
174        let busy_signal = Arc::clone(&config.busy_signal);
175        Box::pin(SignaledFuture::new(busy_signal, async move {
176            let (id, worker_id) = (config.id, config.worker_id);
177            let [
178                data_cap_set,
179                upper_cap_set,
180                definite_error_cap_set,
181                probe_cap,
182            ]: &mut [_; 4] = caps.try_into().unwrap();
183
184            if !config.responsible_for("slot") {
185                // Emit 0, to mark this worker as having started up correctly.
186                for stat in config.statistics.values() {
187                    stat.set_offset_known(0);
188                    stat.set_offset_committed(0);
189                }
190                return Ok(());
191            }
192
193            // Determine the slot lsn.
194            let connection_config = connection
195                .connection
196                .config(
197                    &config.config.connection_context.secrets_reader,
198                    &config.config,
199                    InTask::Yes,
200                )
201                .await?;
202
203            let slot = &connection.publication_details.slot;
204            let replication_client = connection_config
205                .connect_replication(&config.config.connection_context.ssh_tunnel_manager)
206                .await?;
207
208            let metadata_client = connection_config
209                .connect(
210                    "replication metadata",
211                    &config.config.connection_context.ssh_tunnel_manager,
212                )
213                .await?;
214            let metadata_client = Arc::new(metadata_client);
215
216            while let Some(_) = slot_ready_input.next().await {
217                // Wait for the slot to be created
218            }
219
220            // The slot is always created by the snapshot operator. If the slot doesn't exist,
221            // when this check runs, this operator will return an error.
222            let slot_metadata = super::fetch_slot_metadata(
223                &*metadata_client,
224                slot,
225                mz_storage_types::dyncfgs::PG_FETCH_SLOT_RESUME_LSN_INTERVAL
226                    .get(config.config.config_set()),
227            )
228            .await?;
229
230            // We're the only application that should be using this replication
231            // slot. The only way that there can be another connection using
232            // this slot under normal operation is if there's a stale TCP
233            // connection from a prior incarnation of the source holding on to
234            // the slot. We don't want to wait for the WAL sender timeout and/or
235            // TCP keepalives to time out that connection, because these values
236            // are generally under the control of the DBA and may not time out
237            // the connection for multiple minutes, or at all. Instead we just
238            // force kill the connection that's using the slot.
239            //
240            // Note that there's a small risk that *we're* the zombie cluster
241            // that should not be using the replication slot. Kubernetes cannot
242            // 100% guarantee that only one cluster is alive at a time. However,
243            // this situation should not last long, and the worst that can
244            // happen is a bit of transient thrashing over ownership of the
245            // replication slot.
246            if let Some(active_pid) = slot_metadata.active_pid {
247                tracing::warn!(
248                    %id, %active_pid,
249                    "replication slot already in use; will attempt to kill existing connection",
250                );
251
252                match metadata_client
253                    .execute("SELECT pg_terminate_backend($1)", &[&active_pid])
254                    .await
255                {
256                    Ok(_) => {
257                        tracing::info!(
258                            "successfully killed existing connection; \
259                            starting replication is likely to succeed"
260                        );
261                        // Note that `pg_terminate_backend` does not wait for
262                        // the termination of the targeted connection to
263                        // complete. We may try to start replication before the
264                        // targeted connection has cleaned up its state. That's
265                        // okay. If that happens we'll just try again from the
266                        // top via the suspend-and-restart flow.
267                    }
268                    Err(e) => {
269                        tracing::warn!(
270                            %e,
271                            "failed to kill existing replication connection; \
272                            replication will likely fail to start"
273                        );
274                        // Continue on anyway, just in case the replication slot
275                        // is actually available. Maybe PostgreSQL has some
276                        // staleness when it reports `active_pid`, for example.
277                    }
278                }
279            }
280
281            // The overall resumption point for this source is the minimum of the resumption points
282            // contributed by each of the outputs.
283            let resume_lsn = output_uppers
284                .iter()
285                .flat_map(|f| f.elements())
286                .map(|&lsn| {
287                    // An output is either an output that has never had data committed to it or one
288                    // that has and needs to resume. We differentiate between the two by checking
289                    // whether an output wishes to "resume" from the minimum timestamp. In that case
290                    // its contribution to the overal resumption point is the earliest point available
291                    // in the slot. This information would normally be something that the storage
292                    // controller figures out in the form of an as-of frontier, but at the moment the
293                    // storage controller does not have visibility into what the replication slot is
294                    // doing.
295                    if lsn == MzOffset::from(0) {
296                        slot_metadata.confirmed_flush_lsn
297                    } else {
298                        lsn
299                    }
300                })
301                .min();
302            let Some(resume_lsn) = resume_lsn else {
303                std::future::pending::<()>().await;
304                return Ok(());
305            };
306            upper_cap_set.downgrade([&resume_lsn]);
307            trace!(%id, "timely-{worker_id} replication reader started lsn={resume_lsn}");
308
309            // Emitting an initial probe before we start waiting for rewinds ensures that we will
310            // have a timestamp binding in the remap collection while the snapshot is processed.
311            // This is important because otherwise the snapshot updates would need to be buffered
312            // in the reclock operator, instead of being spilled to S3 in the persist sink.
313            //
314            // Note that we need to fetch the probe LSN _after_ having created the replication
315            // slot, to make sure the fetched LSN will be included in the replication stream.
316            let probe_ts = (config.now_fn)().into();
317            let max_lsn = super::fetch_max_lsn(&*metadata_client).await?;
318            let probe = Probe {
319                probe_ts,
320                upstream_frontier: Antichain::from_elem(max_lsn),
321            };
322            probe_output.give(&probe_cap[0], probe);
323
324            let mut rewinds = BTreeMap::new();
325            while let Some(event) = rewind_input.next().await {
326                if let AsyncEvent::Data(_, data) = event {
327                    for req in data {
328                        if resume_lsn > req.snapshot_lsn + 1 {
329                            let err = DefiniteError::SlotCompactedPastResumePoint(
330                                req.snapshot_lsn + 1,
331                                resume_lsn,
332                            );
333                            // If the replication stream cannot be obtained from the resume point there is nothing
334                            // else to do. These errors are not retractable.
335                            for (oid, outputs) in table_info.iter() {
336                                for output_index in outputs.keys() {
337                                    // We pick `u64::MAX` as the LSN which will (in practice) never conflict
338                                    // any previously revealed portions of the TVC.
339                                    let update = (
340                                        (
341                                            *oid,
342                                            *output_index,
343                                            Err(DataflowError::from(err.clone())),
344                                        ),
345                                        MzOffset::from(u64::MAX),
346                                        Diff::ONE,
347                                    );
348                                    data_output.give_fueled(&data_cap_set[0], update).await;
349                                }
350                            }
351                            definite_error_handle.give(
352                                &definite_error_cap_set[0],
353                                ReplicationError::Definite(Rc::new(err)),
354                            );
355                            return Ok(());
356                        }
357                        rewinds.insert(req.output_index, req);
358                    }
359                }
360            }
361            trace!(%id, "timely-{worker_id} pending rewinds {rewinds:?}");
362
363            let mut committed_uppers = pin!(committed_uppers);
364
365            let stream_result = raw_stream(
366                &config,
367                replication_client,
368                Arc::clone(&metadata_client),
369                &connection.publication_details.slot,
370                &connection.publication_details.timeline_id,
371                &connection.publication,
372                resume_lsn,
373                committed_uppers.as_mut(),
374                &probe_output,
375                &probe_cap[0],
376            )
377            .await?;
378
379            let stream = match stream_result {
380                Ok(stream) => stream,
381                Err(err) => {
382                    // If the replication stream cannot be obtained in a definite way there is
383                    // nothing else to do. These errors are not retractable.
384                    for (oid, outputs) in table_info.iter() {
385                        for output_index in outputs.keys() {
386                            // We pick `u64::MAX` as the LSN which will (in practice) never conflict
387                            // any previously revealed portions of the TVC.
388                            let update = (
389                                (*oid, *output_index, Err(DataflowError::from(err.clone()))),
390                                MzOffset::from(u64::MAX),
391                                Diff::ONE,
392                            );
393                            data_output.give_fueled(&data_cap_set[0], update).await;
394                        }
395                    }
396
397                    definite_error_handle.give(
398                        &definite_error_cap_set[0],
399                        ReplicationError::Definite(Rc::new(err)),
400                    );
401                    return Ok(());
402                }
403            };
404            let mut stream = pin!(stream.peekable());
405
406            // Run the periodic schema validation on a separate task using a separate client,
407            // to prevent it from blocking the replication reading progress.
408            let ssh_tunnel_manager = &config.config.connection_context.ssh_tunnel_manager;
409            let client = connection_config
410                .connect("schema validation", ssh_tunnel_manager)
411                .await?;
412            let mut schema_errors = spawn_schema_validator(
413                client,
414                &config,
415                connection.publication.clone(),
416                table_info.clone(),
417            );
418
419            // Instead of downgrading the capability for every transaction we process we only do it
420            // if we're about to yield, which is checked at the bottom of the loop. This avoids
421            // creating excessive progress tracking traffic when there are multiple small
422            // transactions ready to go.
423            let mut data_upper = resume_lsn;
424            // A stash of reusable vectors to convert from bytes::Bytes based data, which is not
425            // compatible with `columnation`, to Vec<u8> data that is.
426            while let Some(event) = stream.as_mut().next().await {
427                use LogicalReplicationMessage::*;
428                use ReplicationMessage::*;
429                match event {
430                    Ok(XLogData(data)) => match data.data() {
431                        Begin(begin) => {
432                            let commit_lsn = MzOffset::from(begin.final_lsn());
433
434                            let mut tx = pin!(extract_transaction(
435                                stream.by_ref(),
436                                &*metadata_client,
437                                commit_lsn,
438                                &mut table_info,
439                                &metrics,
440                                &connection.publication,
441                            ));
442
443                            trace!(
444                                %id,
445                                "timely-{worker_id} extracting transaction \
446                                    at {commit_lsn}"
447                            );
448                            assert!(
449                                data_upper <= commit_lsn,
450                                "new_upper={data_upper} tx_lsn={commit_lsn}",
451                            );
452                            data_upper = commit_lsn + 1;
453                            // We are about to ingest a transaction which has the possiblity to be
454                            // very big and we certainly don't want to hold the data in memory. For
455                            // this reason we eagerly downgrade the upper capability in order for
456                            // the reclocking machinery to mint a binding that includes
457                            // this transaction and therefore be able to pass the data of the
458                            // transaction through as we stream it.
459                            upper_cap_set.downgrade([&data_upper]);
460                            while let Some((oid, output_index, event, diff)) = tx.try_next().await?
461                            {
462                                let event = event.map_err(Into::into);
463                                let mut data = (oid, output_index, event);
464                                if let Some(req) = rewinds.get(&output_index) {
465                                    if commit_lsn <= req.snapshot_lsn {
466                                        let update = (data, MzOffset::from(0), -diff);
467                                        data_output.give_fueled(&data_cap_set[0], &update).await;
468                                        data = update.0;
469                                    }
470                                }
471                                let update = (data, commit_lsn, diff);
472                                data_output.give_fueled(&data_cap_set[0], &update).await;
473                            }
474                        }
475                        _ => return Err(TransientError::BareTransactionEvent),
476                    },
477                    Ok(PrimaryKeepAlive(keepalive)) => {
478                        trace!( %id,
479                            "timely-{worker_id} received keepalive lsn={}",
480                            keepalive.wal_end()
481                        );
482
483                        // Take the opportunity to report any schema validation errors.
484                        while let Ok(error) = schema_errors.try_recv() {
485                            use SchemaValidationError::*;
486                            match error {
487                                Postgres(PostgresError::PublicationMissing(publication)) => {
488                                    let err = DefiniteError::PublicationDropped(publication);
489                                    for (oid, outputs) in table_info.iter() {
490                                        for output_index in outputs.keys() {
491                                            let update = (
492                                                (
493                                                    *oid,
494                                                    *output_index,
495                                                    Err(DataflowError::from(err.clone())),
496                                                ),
497                                                data_cap_set[0].time().clone(),
498                                                Diff::ONE,
499                                            );
500                                            data_output.give_fueled(&data_cap_set[0], update).await;
501                                        }
502                                    }
503                                    definite_error_handle.give(
504                                        &definite_error_cap_set[0],
505                                        ReplicationError::Definite(Rc::new(err)),
506                                    );
507                                    return Ok(());
508                                }
509                                Postgres(pg_error) => Err(TransientError::from(pg_error))?,
510                                Schema {
511                                    oid,
512                                    output_index,
513                                    error,
514                                } => {
515                                    let table = table_info.get_mut(&oid).unwrap();
516                                    if table.remove(&output_index).is_none() {
517                                        continue;
518                                    }
519
520                                    let update = (
521                                        (oid, output_index, Err(error.into())),
522                                        data_cap_set[0].time().clone(),
523                                        Diff::ONE,
524                                    );
525                                    data_output.give_fueled(&data_cap_set[0], update).await;
526                                }
527                            }
528                        }
529                        data_upper = std::cmp::max(data_upper, keepalive.wal_end().into());
530                    }
531                    Ok(_) => return Err(TransientError::UnknownReplicationMessage),
532                    Err(err) => return Err(err),
533                }
534
535                let will_yield = stream.as_mut().peek().now_or_never().is_none();
536                if will_yield {
537                    trace!(%id, "timely-{worker_id} yielding at lsn={data_upper}");
538                    rewinds.retain(|_, req| data_upper <= req.snapshot_lsn);
539                    // As long as there are pending rewinds we can't downgrade our data capability
540                    // since we must be able to produce data at offset 0.
541                    if rewinds.is_empty() {
542                        data_cap_set.downgrade([&data_upper]);
543                    }
544                    upper_cap_set.downgrade([&data_upper]);
545                }
546            }
547            // We never expect the replication stream to gracefully end
548            Err(TransientError::ReplicationEOF)
549        }))
550    });
551
552    // We now process the slot updates and apply the cast expressions
553    let mut final_row = Row::default();
554    let mut datum_vec = DatumVec::new();
555    let mut next_worker = (0..u64::cast_from(scope.peers()))
556        // Round robin on 1000-records basis to avoid creating tiny containers when there are a
557        // small number of updates and a large number of workers.
558        .flat_map(|w| std::iter::repeat_n(w, 1000))
559        .cycle();
560    let round_robin = Exchange::new(move |_| next_worker.next().unwrap());
561    let replication_updates = data_stream
562        .map::<Vec<_>, _, _>(Clone::clone)
563        .unary(round_robin, "PgCastReplicationRows", |_, _| {
564            move |input, output| {
565                input.for_each_time(|time, data| {
566                    let mut session = output.session(&time);
567                    for ((oid, output_index, event), time, diff) in
568                        data.flat_map(|data| data.drain(..))
569                    {
570                        let output = &table_info
571                            .get(&oid)
572                            .and_then(|outputs| outputs.get(&output_index))
573                            .expect("table_info contains all outputs");
574                        let event = event.and_then(|row| {
575                            let datums = datum_vec.borrow_with(&row);
576                            super::cast_row(&output.casts, &datums, &mut final_row)?;
577                            Ok(SourceMessage {
578                                key: Row::default(),
579                                value: final_row.clone(),
580                                metadata: Row::default(),
581                            })
582                        });
583
584                        session.give(((output_index, event), time, diff));
585                    }
586                });
587            }
588        })
589        .as_collection();
590
591    let errors = definite_errors.concat(&transient_errors.map(ReplicationError::from));
592
593    (
594        replication_updates,
595        upper_stream,
596        Some(probe_stream),
597        errors,
598        button.press_on_drop(),
599    )
600}
601
602/// Produces the logical replication stream while taking care of regularly sending standby
603/// keepalive messages with the provided `uppers` stream.
604///
605/// The returned stream will contain all transactions that whose commit LSN is beyond `resume_lsn`.
606async fn raw_stream<'a>(
607    config: &'a RawSourceCreationConfig,
608    replication_client: Client,
609    metadata_client: Arc<Client>,
610    slot: &'a str,
611    timeline_id: &'a Option<u64>,
612    publication: &'a str,
613    resume_lsn: MzOffset,
614    uppers: impl futures::Stream<Item = Antichain<MzOffset>> + 'a,
615    probe_output: &'a AsyncOutputHandle<MzOffset, CapacityContainerBuilder<Vec<Probe<MzOffset>>>>,
616    probe_cap: &'a Capability<MzOffset>,
617) -> Result<
618    Result<
619        impl AsyncStream<Item = Result<ReplicationMessage<LogicalReplicationMessage>, TransientError>>
620        + 'a,
621        DefiniteError,
622    >,
623    TransientError,
624> {
625    if let Err(err) = ensure_publication_exists(&*metadata_client, publication).await? {
626        // If the publication gets deleted there is nothing else to do. These errors
627        // are not retractable.
628        return Ok(Err(err));
629    }
630
631    // Skip the timeline ID check for sources without a known timeline ID
632    // (sources created before the timeline ID was added to the source details)
633    if let Some(expected_timeline_id) = timeline_id {
634        if let Err(err) =
635            ensure_replication_timeline_id(&replication_client, expected_timeline_id).await?
636        {
637            return Ok(Err(err));
638        }
639    }
640
641    // How often a proactive standby status update message should be sent to the server.
642    //
643    // The upstream will periodically request status updates by setting the keepalive's reply field
644    // value to 1. However, we cannot rely on these messages arriving on time. For example, when
645    // the upstream is sending a big transaction its keepalive messages are queued and can be
646    // delayed arbitrarily.
647    //
648    // See: <https://www.postgresql.org/message-id/CAMsr+YE2dSfHVr7iEv1GSPZihitWX-PMkD9QALEGcTYa+sdsgg@mail.gmail.com>
649    //
650    // For this reason we query the server's timeout value and proactively send a keepalive at
651    // twice the frequency to have a healthy margin from the deadline.
652    //
653    // Note: We must use the metadata client here which is NOT in replication mode. Some Aurora
654    // Postgres versions disallow SHOW commands from within replication connection.
655    // See: https://github.com/readysettech/readyset/discussions/28#discussioncomment-4405671
656    let row = simple_query_opt(&*metadata_client, "SHOW wal_sender_timeout;")
657        .await?
658        .unwrap();
659    let wal_sender_timeout = match row.get("wal_sender_timeout") {
660        // When this parameter is zero the timeout mechanism is disabled
661        Some("0") => None,
662        Some(value) => Some(
663            mz_repr::adt::interval::Interval::from_str(value)
664                .unwrap()
665                .duration()
666                .unwrap(),
667        ),
668        None => panic!("ubiquitous parameter missing"),
669    };
670
671    // This interval controls the cadence at which we send back status updates and, crucially,
672    // request PrimaryKeepAlive messages. PrimaryKeepAlive messages drive the frontier forward in
673    // the absence of data updates and we don't want a large `wal_sender_timeout` value to slow us
674    // down. For this reason the feedback interval is set to one second, or less if the
675    // wal_sender_timeout is less than 2 seconds.
676    let feedback_interval = match wal_sender_timeout {
677        Some(t) => std::cmp::min(Duration::from_secs(1), t.checked_div(2).unwrap()),
678        None => Duration::from_secs(1),
679    };
680
681    let mut feedback_timer = tokio::time::interval(feedback_interval);
682    // 'Delay' ensures we always tick at least 'feedback_interval'.
683    feedback_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
684
685    // Postgres will return all transactions that commit *at or after* after the provided LSN,
686    // following the timely upper semantics.
687    let lsn = PgLsn::from(resume_lsn.offset);
688    let query = format!(
689        r#"START_REPLICATION SLOT "{}" LOGICAL {} ("proto_version" '1', "publication_names" '{}')"#,
690        Ident::new_unchecked(slot).to_ast_string_simple(),
691        lsn,
692        publication,
693    );
694    let copy_stream = match replication_client.copy_both_simple(&query).await {
695        Ok(copy_stream) => copy_stream,
696        Err(err) if err.code() == Some(&SqlState::OBJECT_NOT_IN_PREREQUISITE_STATE) => {
697            return Ok(Err(DefiniteError::InvalidReplicationSlot));
698        }
699        Err(err) => return Err(err.into()),
700    };
701
702    // According to the documentation [1] we must check that the slot LSN matches our
703    // expectations otherwise we risk getting silently fast-forwarded to a future LSN. In order
704    // to avoid a TOCTOU issue we must do this check after starting the replication stream. We
705    // cannot use the replication client to do that because it's already in CopyBoth mode.
706    // [1] https://www.postgresql.org/docs/15/protocol-replication.html#PROTOCOL-REPLICATION-START-REPLICATION-SLOT-LOGICAL
707    let slot_metadata = super::fetch_slot_metadata(
708        &*metadata_client,
709        slot,
710        mz_storage_types::dyncfgs::PG_FETCH_SLOT_RESUME_LSN_INTERVAL
711            .get(config.config.config_set()),
712    )
713    .await?;
714    let min_resume_lsn = slot_metadata.confirmed_flush_lsn;
715    tracing::info!(
716        %config.id,
717        "started replication using backend PID={:?}. wal_sender_timeout={:?}",
718        slot_metadata.active_pid, wal_sender_timeout
719    );
720
721    let (probe_tx, mut probe_rx) = watch::channel(None);
722    let config_set = Arc::clone(config.config.config_set());
723    let now_fn = config.now_fn.clone();
724    let max_lsn_task_handle =
725        mz_ore::task::spawn(|| format!("pg_current_wal_lsn:{}", config.id), async move {
726            let mut probe_ticker =
727                probe::Ticker::new(|| PG_OFFSET_KNOWN_INTERVAL.get(&config_set), now_fn);
728
729            while !probe_tx.is_closed() {
730                let probe_ts = probe_ticker.tick().await;
731                let probe_or_err = super::fetch_max_lsn(&*metadata_client)
732                    .await
733                    .map(|lsn| Probe {
734                        probe_ts,
735                        upstream_frontier: Antichain::from_elem(lsn),
736                    });
737                let _ = probe_tx.send(Some(probe_or_err));
738            }
739        })
740        .abort_on_drop();
741
742    let stream = async_stream::try_stream!({
743        // Ensure we don't pre-drop the task
744        let _max_lsn_task_handle = max_lsn_task_handle;
745
746        // ensure we don't drop the replication client!
747        let _replication_client = replication_client;
748
749        let mut uppers = pin!(uppers);
750        let mut last_committed_upper = resume_lsn;
751
752        let mut stream = pin!(LogicalReplicationStream::new(copy_stream));
753
754        if !(resume_lsn == MzOffset::from(0) || min_resume_lsn <= resume_lsn) {
755            let err = TransientError::OvercompactedReplicationSlot {
756                available_lsn: min_resume_lsn,
757                requested_lsn: resume_lsn,
758            };
759            error!("timely-{} ({}) {err}", config.worker_id, config.id);
760            Err(err)?;
761        }
762
763        loop {
764            tokio::select! {
765                Some(next_message) = stream.next() => match next_message {
766                    Ok(ReplicationMessage::XLogData(data)) => {
767                        yield ReplicationMessage::XLogData(data);
768                        Ok(())
769                    }
770                    Ok(ReplicationMessage::PrimaryKeepAlive(keepalive)) => {
771                        yield ReplicationMessage::PrimaryKeepAlive(keepalive);
772                        Ok(())
773                    }
774                    Err(err) => Err(err.into()),
775                    _ => Err(TransientError::UnknownReplicationMessage),
776                },
777                _ = feedback_timer.tick() => {
778                    let ts: i64 = PG_EPOCH.elapsed().unwrap().as_micros().try_into().unwrap();
779                    let lsn = PgLsn::from(last_committed_upper.offset);
780                    trace!("timely-{} ({}) sending keepalive {lsn:?}", config.worker_id, config.id);
781                    // Postgres only sends PrimaryKeepAlive messages when *it* wants a reply, which
782                    // happens when out status update is late. Since we send them proactively this
783                    // may never happen. It is therefore *crucial* that we set the last parameter
784                    // (the reply flag) to 1 here. This will cause the upstream server to send us a
785                    // PrimaryKeepAlive message promptly which will give us frontier advancement
786                    // information in the absence of data updates.
787                    let res = stream.as_mut().standby_status_update(lsn, lsn, lsn, ts, 1).await;
788                    res.map_err(|e| e.into())
789                },
790                Some(upper) = uppers.next() => match upper.into_option() {
791                    Some(lsn) => {
792                        if last_committed_upper < lsn {
793                            last_committed_upper = lsn;
794                            for stat in config.statistics.values() {
795                                stat.set_offset_committed(last_committed_upper.offset);
796                            }
797                        }
798                        Ok(())
799                    }
800                    None => Ok(()),
801                },
802                Ok(()) = probe_rx.changed() => match &*probe_rx.borrow() {
803                    Some(Ok(probe)) => {
804                        if let Some(offset_known) = probe.upstream_frontier.as_option() {
805                            for stat in config.statistics.values() {
806                                stat.set_offset_known(offset_known.offset);
807                            }
808                        }
809                        probe_output.give(probe_cap, probe);
810                        Ok(())
811                    },
812                    Some(Err(err)) => Err(anyhow::anyhow!("{err}").into()),
813                    None => Ok(()),
814                },
815                else => return
816            }?;
817        }
818    });
819    Ok(Ok(stream))
820}
821
822/// Extracts a single transaction from the replication stream delimited by a BEGIN and COMMIT
823/// message. The BEGIN message must have already been consumed from the stream before calling this
824/// function.
825fn extract_transaction<'a>(
826    stream: impl AsyncStream<
827        Item = Result<ReplicationMessage<LogicalReplicationMessage>, TransientError>,
828    > + 'a,
829    metadata_client: &'a Client,
830    commit_lsn: MzOffset,
831    table_info: &'a mut BTreeMap<u32, BTreeMap<usize, SourceOutputInfo>>,
832    metrics: &'a PgSourceMetrics,
833    publication: &'a str,
834) -> impl AsyncStream<Item = Result<(u32, usize, Result<Row, DefiniteError>, Diff), TransientError>> + 'a
835{
836    use LogicalReplicationMessage::*;
837    let mut row = Row::default();
838    async_stream::try_stream!({
839        let mut stream = pin!(stream);
840        metrics.transactions.inc();
841        metrics.lsn.set(commit_lsn.offset);
842        while let Some(event) = stream.try_next().await? {
843            // We can ignore keepalive messages while processing a transaction because the
844            // commit_lsn will drive progress.
845            let message = match event {
846                ReplicationMessage::XLogData(data) => data.into_data(),
847                ReplicationMessage::PrimaryKeepAlive(_) => {
848                    metrics.ignored.inc();
849                    continue;
850                }
851                _ => Err(TransientError::UnknownReplicationMessage)?,
852            };
853            metrics.total.inc();
854            match message {
855                Insert(body) if !table_info.contains_key(&body.rel_id()) => metrics.ignored.inc(),
856                Update(body) if !table_info.contains_key(&body.rel_id()) => metrics.ignored.inc(),
857                Delete(body) if !table_info.contains_key(&body.rel_id()) => metrics.ignored.inc(),
858                Relation(body) if !table_info.contains_key(&body.rel_id()) => metrics.ignored.inc(),
859                Insert(body) => {
860                    metrics.inserts.inc();
861                    let rel = body.rel_id();
862                    for (output, info) in table_info.get(&rel).into_iter().flatten() {
863                        let tuple_data = body.tuple().tuple_data();
864                        let Some(ref projection) = info.projection else {
865                            panic!("missing projection for {rel}");
866                        };
867                        let datums = projection.iter().map(|idx| &tuple_data[*idx]);
868                        let row = unpack_tuple(datums, &mut row);
869                        yield (rel, *output, row, Diff::ONE);
870                    }
871                }
872                Update(body) => match body.old_tuple() {
873                    Some(old_tuple) => {
874                        metrics.updates.inc();
875                        let new_tuple = body.new_tuple();
876                        let rel = body.rel_id();
877                        for (output, info) in table_info.get(&rel).into_iter().flatten() {
878                            let Some(ref projection) = info.projection else {
879                                panic!("missing projection for {rel}");
880                            };
881                            let old_tuple =
882                                projection.iter().map(|idx| &old_tuple.tuple_data()[*idx]);
883                            // If the new tuple contains unchanged toast values we reference the old ones
884                            let new_tuple = std::iter::zip(
885                                projection.iter().map(|idx| &new_tuple.tuple_data()[*idx]),
886                                old_tuple.clone(),
887                            )
888                            .map(|(new, old)| match new {
889                                TupleData::UnchangedToast => old,
890                                _ => new,
891                            });
892                            let old_row = unpack_tuple(old_tuple, &mut row);
893                            let new_row = unpack_tuple(new_tuple, &mut row);
894
895                            yield (rel, *output, old_row, Diff::MINUS_ONE);
896                            yield (rel, *output, new_row, Diff::ONE);
897                        }
898                    }
899                    None => {
900                        let rel = body.rel_id();
901                        for (output, _) in table_info.get(&rel).into_iter().flatten() {
902                            yield (
903                                rel,
904                                *output,
905                                Err(DefiniteError::DefaultReplicaIdentity),
906                                Diff::ONE,
907                            );
908                        }
909                    }
910                },
911                Delete(body) => match body.old_tuple() {
912                    Some(old_tuple) => {
913                        metrics.deletes.inc();
914                        let rel = body.rel_id();
915                        for (output, info) in table_info.get(&rel).into_iter().flatten() {
916                            let Some(ref projection) = info.projection else {
917                                panic!("missing projection for {rel}");
918                            };
919                            let datums = projection.iter().map(|idx| &old_tuple.tuple_data()[*idx]);
920                            let row = unpack_tuple(datums, &mut row);
921                            yield (rel, *output, row, Diff::MINUS_ONE);
922                        }
923                    }
924                    None => {
925                        let rel = body.rel_id();
926                        for (output, _) in table_info.get(&rel).into_iter().flatten() {
927                            yield (
928                                rel,
929                                *output,
930                                Err(DefiniteError::DefaultReplicaIdentity),
931                                Diff::ONE,
932                            );
933                        }
934                    }
935                },
936                Relation(body) => {
937                    let rel_id = body.rel_id();
938                    if let Some(outputs) = table_info.get_mut(&body.rel_id()) {
939                        // Because the replication stream doesn't include columns' attnums, we need
940                        // to check the current local schema against the current remote schema to
941                        // ensure e.g. we haven't received a schema update with the same terminal
942                        // column name which is actually a different column.
943                        let upstream_info = mz_postgres_util::publication_info(
944                            metadata_client,
945                            publication,
946                            Some(&[rel_id]),
947                        )
948                        .await?;
949
950                        let mut schema_errors = vec![];
951
952                        outputs.retain(|output_index, info| {
953                            match verify_schema(rel_id, info, &upstream_info) {
954                                Ok(()) => true,
955                                Err(err) => {
956                                    schema_errors.push((
957                                        rel_id,
958                                        *output_index,
959                                        Err(err),
960                                        Diff::ONE,
961                                    ));
962                                    false
963                                }
964                            }
965                        });
966                        // Recalculate projection vector for the retained valid outputs. Here we
967                        // must use the column names in the RelationBody message and not the
968                        // upstream_info obtained above, since that one represents the current
969                        // schema upstream which may be many versions head of the one we're about
970                        // to receive after this Relation message.
971                        let column_positions: BTreeMap<_, _> = body
972                            .columns()
973                            .iter()
974                            .enumerate()
975                            .map(|(idx, col)| (col.name().unwrap(), idx))
976                            .collect();
977                        for info in outputs.values_mut() {
978                            let mut projection = vec![];
979                            for col in info.desc.columns.iter() {
980                                projection.push(column_positions[&*col.name]);
981                            }
982                            info.projection = Some(projection);
983                        }
984                        for schema_error in schema_errors {
985                            yield schema_error;
986                        }
987                    }
988                }
989                Truncate(body) => {
990                    for &rel_id in body.rel_ids() {
991                        if let Some(outputs) = table_info.get_mut(&rel_id) {
992                            for (output, _) in std::mem::take(outputs) {
993                                yield (
994                                    rel_id,
995                                    output,
996                                    Err(DefiniteError::TableTruncated),
997                                    Diff::ONE,
998                                );
999                            }
1000                        }
1001                    }
1002                }
1003                Commit(body) => {
1004                    if commit_lsn != body.commit_lsn().into() {
1005                        Err(TransientError::InvalidTransaction)?
1006                    }
1007                    return;
1008                }
1009                // TODO: We should handle origin messages and emit an error as they indicate that
1010                // the upstream performed a point in time restore so all bets are off about the
1011                // continuity of the stream.
1012                Origin(_) | Type(_) => metrics.ignored.inc(),
1013                Begin(_) => Err(TransientError::NestedTransaction)?,
1014                // The enum is marked as non_exhaustive. Better to be conservative
1015                _ => Err(TransientError::UnknownLogicalReplicationMessage)?,
1016            }
1017        }
1018        Err(TransientError::ReplicationEOF)?;
1019    })
1020}
1021
1022/// Unpacks an iterator of TupleData into a list of nullable bytes or an error if this can't be
1023/// done.
1024#[inline]
1025fn unpack_tuple<'a, I>(tuple_data: I, row: &mut Row) -> Result<Row, DefiniteError>
1026where
1027    I: IntoIterator<Item = &'a TupleData>,
1028    I::IntoIter: ExactSizeIterator,
1029{
1030    let iter = tuple_data.into_iter();
1031    let mut packer = row.packer();
1032    for data in iter {
1033        let datum = match data {
1034            TupleData::Text(bytes) => super::decode_utf8_text(bytes)?,
1035            TupleData::Null => Datum::Null,
1036            TupleData::UnchangedToast => return Err(DefiniteError::MissingToast),
1037            TupleData::Binary(_) => return Err(DefiniteError::UnexpectedBinaryData),
1038        };
1039        packer.push(datum);
1040    }
1041    Ok(row.clone())
1042}
1043
1044/// Ensures the publication exists on the server. It returns an outer transient error in case of
1045/// connection issues and an inner definite error if the publication is dropped.
1046async fn ensure_publication_exists(
1047    client: &Client,
1048    publication: &str,
1049) -> Result<Result<(), DefiniteError>, TransientError> {
1050    // Figure out the last written LSN and then add one to convert it into an upper.
1051    let result = client
1052        .query_opt(
1053            "SELECT 1 FROM pg_publication WHERE pubname = $1;",
1054            &[&publication],
1055        )
1056        .await?;
1057    match result {
1058        Some(_) => Ok(Ok(())),
1059        None => Ok(Err(DefiniteError::PublicationDropped(
1060            publication.to_owned(),
1061        ))),
1062    }
1063}
1064
1065/// Ensure the active replication timeline_id matches the one we expect such that we can safely
1066/// resume replication. It returns an outer transient error in case of
1067/// connection issues and an inner definite error if the timeline id does not match.
1068async fn ensure_replication_timeline_id(
1069    replication_client: &Client,
1070    expected_timeline_id: &u64,
1071) -> Result<Result<(), DefiniteError>, TransientError> {
1072    let timeline_id = mz_postgres_util::get_timeline_id(replication_client).await?;
1073    if timeline_id == *expected_timeline_id {
1074        Ok(Ok(()))
1075    } else {
1076        Ok(Err(DefiniteError::InvalidTimelineId {
1077            expected: *expected_timeline_id,
1078            actual: timeline_id,
1079        }))
1080    }
1081}
1082
1083enum SchemaValidationError {
1084    Postgres(PostgresError),
1085    Schema {
1086        oid: u32,
1087        output_index: usize,
1088        error: DefiniteError,
1089    },
1090}
1091
1092fn spawn_schema_validator(
1093    client: Client,
1094    config: &RawSourceCreationConfig,
1095    publication: String,
1096    table_info: BTreeMap<u32, BTreeMap<usize, SourceOutputInfo>>,
1097) -> mpsc::UnboundedReceiver<SchemaValidationError> {
1098    let (tx, rx) = mpsc::unbounded_channel();
1099    let source_id = config.id;
1100    let config_set = Arc::clone(config.config.config_set());
1101
1102    mz_ore::task::spawn(|| format!("schema-validator:{}", source_id), async move {
1103        while !tx.is_closed() {
1104            trace!(%source_id, "validating schemas");
1105
1106            let validation_start = Instant::now();
1107
1108            let upstream_info = match mz_postgres_util::publication_info(
1109                &*client,
1110                &publication,
1111                Some(&table_info.keys().copied().collect::<Vec<_>>()),
1112            )
1113            .await
1114            {
1115                Ok(info) => info,
1116                Err(error) => {
1117                    let _ = tx.send(SchemaValidationError::Postgres(error));
1118                    continue;
1119                }
1120            };
1121
1122            for (&oid, outputs) in table_info.iter() {
1123                for (&output_index, info) in outputs {
1124                    if let Err(error) = verify_schema(oid, info, &upstream_info) {
1125                        trace!(
1126                            %source_id,
1127                            "schema of output index {output_index} for oid {oid} invalid",
1128                        );
1129                        let _ = tx.send(SchemaValidationError::Schema {
1130                            oid,
1131                            output_index,
1132                            error,
1133                        });
1134                    } else {
1135                        trace!(
1136                            %source_id,
1137                            "schema of output index {output_index} for oid {oid} valid",
1138                        );
1139                    }
1140                }
1141            }
1142
1143            let interval = PG_SCHEMA_VALIDATION_INTERVAL.get(&config_set);
1144            let elapsed = validation_start.elapsed();
1145            let wait = interval.saturating_sub(elapsed);
1146            tokio::time::sleep(wait).await;
1147        }
1148    });
1149
1150    rx
1151}