<!-- livebook:{"persist_outputs":true} -->

<!--
SPDX-FileCopyrightText: © 2026 BaseLabs Holdings LLC

SPDX-License-Identifier: MIT
-->

# Getting started with Replicant

Follow this Livebook to build a sink and stream changes from a demo PostgreSQL
database. The tour exercises row changes, unchanged TOAST columns, snapshots,
logical messages and PostgreSQL value casting.

Use the [compatibility guide](../topics/about/compatibility.md) to choose a
server. Allow the demo role to create tables, publications and replication slots.
The notebook owns its demo tables and slots in the database you select.

## Setup

```elixir
Mix.install([
  {:replicant, "~> 3.1"},
  {:kino, "~> 0.14"}
])
```

> **Contributors:** to run against your working tree instead of the published
> package, replace the `:replicant` line with `{:replicant, path: "/path/to/replicant"}`.

## Connect to a logical-replication Postgres

Use a disposable PostgreSQL database with `wal_level = logical`. For a local
sandbox, the [reference pipeline guide](../how-to/reference-deployment.md)
shows the Docker Compose source setup. Enter the connection URL in the field
below. Replicant uses pgoutput for this tour.

```elixir
default_url = System.get_env("REPLICANT_TEST_URL") || "postgres://postgres@localhost:5599/postgres"
url_input = Kino.Input.text("Postgres URL (needs wal_level = logical)", default: default_url)
```

```elixir
# Parse the URL into Postgrex connection options.
db_url = Kino.Input.read(url_input)

pg_opts =
  (fn url ->
     uri = URI.parse(url)

     {user, pass} =
       case uri.userinfo do
         nil ->
           {"postgres", nil}

         ui ->
           case String.split(ui, ":", parts: 2) do
             [u, p] -> {u, p}
             [u] -> {u, nil}
           end
       end

     base = [
       hostname: uri.host || "localhost",
       port: uri.port || 5432,
       database: String.trim_leading(uri.path || "/postgres", "/"),
       username: user
     ]

     if pass, do: base ++ [password: pass], else: base
   end).(db_url)

# A plain (non-replication) connection for issuing demo DML + reading the mirror.
# start-or-reuse so re-running this cell in Livebook is harmless.
sql =
  case Postgrex.start_link(pg_opts ++ [name: :lb_sql, pool_size: 4]) do
    {:ok, pid} -> pid
    {:error, {:already_started, pid}} -> pid
  end

Postgrex.query!(sql, "SELECT 1", [])
:connected
```

## A few small helpers

`LbDemo` wraps the boilerplate every pipeline needs: start-and-wait-until-live,
stop-and-drop-the-slot, and some tiny query helpers. This is the same shape the
library's own integration suite uses.

```elixir
defmodule LbDemo do
  @moduledoc false

  # Poll `fun` every 25 ms until it returns truthy; raise after `tries` polls. The generous
  # default (400 polls ≈ 10 s) absorbs shared-Postgres load jitter and never manufactures a
  # pass — it returns on the FIRST successful poll, so the happy path stays fast.
  def wait_until(fun, tries \\ 400) do
    cond do
      fun.() -> :ok
      tries == 0 -> raise "timed out waiting for a live-Postgres condition"
      true -> Process.sleep(25) && wait_until(fun, tries - 1)
    end
  end

  # Start a pipeline and block until it owns the slot and is streaming. We attach a
  # NAMED handler (`&__MODULE__.on_slot_active/4`) with config rather than an anonymous
  # function — that's the form :telemetry recommends (no per-event performance note).
  def start_pipeline(config) do
    slot = Keyword.fetch!(config, :slot_name)
    ref = make_ref()

    :telemetry.attach(
      {__MODULE__, :active, ref},
      [:replicant, :connection, :slot_active],
      &__MODULE__.on_slot_active/4,
      %{pid: self(), ref: ref}
    )

    {:ok, pid} = Replicant.start_link(config)

    receive do
      {:slot_active, ^ref} -> :ok
    after
      15_000 -> raise "pipeline never reached slot_active for #{slot}"
    end

    :telemetry.detach({__MODULE__, :active, ref})

    wait_until(
      fn -> match?([{_, _}], Registry.lookup(Replicant.Registry, {slot, :connection})) end,
      200
    )

    {:ok, pid}
  end

  # Telemetry handler for [:replicant, :connection, :slot_active] — notifies the waiting caller.
  def on_slot_active(_event, _measure, _meta, %{pid: pid, ref: ref}), do: send(pid, {:slot_active, ref})

  # Stop a pipeline and drop its slot (so it stops pinning WAL).
  def stop(slot) do
    Replicant.stop(slot)
    wait_until(fn -> Registry.lookup(Replicant.Registry, {slot, :pipeline}) == [] end, 200)
    drop_slot(:lb_sql, slot)
    :ok
  end

  def drop_slot(conn, slot, tries \\ 20)

  def drop_slot(conn, slot, 0), do: do_drop_slot(conn, slot)

  def drop_slot(conn, slot, tries) do
    do_drop_slot(conn, slot)
  rescue
    _ ->
      Process.sleep(50)
      drop_slot(conn, slot, tries - 1)
  end

  defp do_drop_slot(conn, slot) do
    Postgrex.query!(
      conn,
      "SELECT pg_drop_replication_slot(slot_name) FROM pg_replication_slots WHERE slot_name = $1",
      [slot]
    )
  end

  def rows(conn, sql, params \\ []), do: Postgrex.query!(conn, sql, params).rows
  def ids(conn, table), do: rows(conn, "SELECT id FROM #{table} ORDER BY id") |> Enum.map(&hd/1)
  def count(conn, table), do: rows(conn, "SELECT count(*) FROM #{table}") |> hd() |> hd()
end
```

`LbCapture` is a tiny in-memory recorder so we can *look at* the real
`%Replicant.Change{}` structs the sink receives.

```elixir
defmodule LbCapture do
  @moduledoc false
  use Agent

  def start do
    case Agent.start_link(fn -> [] end, name: __MODULE__) do
      {:ok, pid} -> pid
      {:error, {:already_started, pid}} -> pid
    end
  end

  def record(changes), do: Agent.update(__MODULE__, fn acc -> acc ++ [changes] end)
  def reset, do: Agent.update(__MODULE__, fn _ -> [] end)
  def all, do: Agent.get(__MODULE__, & &1)
  def any?, do: Agent.get(__MODULE__, &(&1 != []))
end

LbCapture.start()
:ok
```

## Create a demo schema

We create a source table `lb_orders`, a `PUBLICATION` naming it, and a mirror
table the sink will keep in sync. The `SET STORAGE EXTERNAL` on `memo` forces a
large value out-of-line (TOAST) so we can demonstrate the unchanged-TOAST sentinel
later. This cell is idempotent and self-heals any leftover demo slots from a prior
run.

```elixir
# Self-heal: stop any leftover demo pipelines + drop their slots from a prior run.
for slot <- ~w(replicant_lb_core replicant_lb_snapshot replicant_lb_parity replicant_lb_messages) do
  Replicant.stop(slot)
  LbDemo.drop_slot(:lb_sql, slot)
end

ddl = [
  "DROP PUBLICATION IF EXISTS lb_pub",
  "DROP TABLE IF EXISTS lb_orders, lb_sink_orders, lb_sink_cp, lb_sink_calls, lb_cast",
  "CREATE TABLE lb_orders (id int PRIMARY KEY, item text, qty int, memo text)",
  "ALTER TABLE lb_orders ALTER COLUMN memo SET STORAGE EXTERNAL",
  "CREATE TABLE lb_sink_orders (id int PRIMARY KEY, item text, qty int)",
  "CREATE TABLE lb_sink_cp (id int PRIMARY KEY, lsn bigint)",
  "CREATE TABLE lb_sink_calls (seq bigserial PRIMARY KEY, lsn bigint, outcome text)",
  "CREATE PUBLICATION lb_pub FOR TABLE lb_orders"
]

for stmt <- ddl, do: Postgrex.query!(sql, stmt, [])
:schema_ready
```

## Define a sink and start the pipeline

`LbCoreSink` handles `lb_orders`. The casting exercise adds a second table
to the publication so you can see a sink receive changes it chooses to skip.
See [delivery guarantees](../topics/delivery/invariants.md) for the atomic
checkpoint rule this sink implements.

```elixir
defmodule LbCoreSink do
  @moduledoc false
  @behaviour Replicant.Sink

  alias Replicant.{Change, Transaction}

  @conn :lb_sql

  @impl true
  def checkpoint do
    case Postgrex.query(@conn, "SELECT lsn FROM lb_sink_cp WHERE id = 1", []) do
      {:ok, %Postgrex.Result{rows: [[lsn]]}} -> {:ok, lsn}
      {:ok, %Postgrex.Result{rows: []}} -> {:ok, nil}
      {:error, _} = err -> err
    end
  end

  @impl true
  def handle_transaction(%Transaction{commit_lsn: lsn, changes: changes}) do
    change_list = Enum.to_list(changes)

    result =
      Postgrex.transaction(@conn, fn c ->
        case current_cp(c) do
          cp when is_integer(cp) and lsn <= cp ->
            record_call(c, lsn, "skipped")

          _not_yet_applied ->
            Enum.each(change_list, &apply_change(c, &1))
            set_cp(c, lsn)
            record_call(c, lsn, "applied")
        end
      end)

    # Record the delivered changes so the notebook can display the real structs.
    LbCapture.record(change_list)

    case result do
      {:ok, _} -> {:ok, lsn}
      {:error, reason} -> {:error, reason}
    end
  end

  defp current_cp(c) do
    case Postgrex.query!(c, "SELECT lsn FROM lb_sink_cp WHERE id = 1", []).rows do
      [[lsn]] -> lsn
      [] -> nil
    end
  end

  defp set_cp(c, lsn) do
    Postgrex.query!(
      c,
      "INSERT INTO lb_sink_cp (id, lsn) VALUES (1, $1) ON CONFLICT (id) DO UPDATE SET lsn = EXCLUDED.lsn",
      [lsn]
    )
  end

  defp record_call(c, lsn, outcome) do
    Postgrex.query!(c, "INSERT INTO lb_sink_calls (lsn, outcome) VALUES ($1, $2)", [lsn, outcome])
  end

  # Mirror ONLY lb_orders; any other table in the publication is a no-op. A real
  # sink switches on `change.table` here.
  defp apply_change(c, %Change{table: "lb_orders", op: op, record: r})
       when op in [:insert, :update] do
    Postgrex.query!(
      c,
      "INSERT INTO lb_sink_orders (id, item, qty) VALUES ($1, $2, $3) " <>
        "ON CONFLICT (id) DO UPDATE SET " <>
        "item = COALESCE(EXCLUDED.item, lb_sink_orders.item), " <>
        "qty = COALESCE(EXCLUDED.qty, lb_sink_orders.qty)",
      [r["id"], r["item"], r["qty"]]
    )
  end

  defp apply_change(c, %Change{table: "lb_orders", op: :delete, old_record: old}) do
    Postgrex.query!(c, "DELETE FROM lb_sink_orders WHERE id = $1", [old["id"]])
  end

  defp apply_change(_c, _other_table_change), do: :ok
end
```

This first pipeline uses `go_forward_only: true`. The next exercise uses a
snapshot to start from existing data.

```elixir
core_slot = "replicant_lb_core"

{:ok, _pipeline} =
  LbDemo.start_pipeline(
    connection: pg_opts,
    slot_name: core_slot,
    publication: "lb_pub",
    sink: LbCoreSink,
    go_forward_only: true
  )

:streaming
```

## Watch changes flow

Insert three rows, update one, then delete one. Each `Postgrex.query!` commits
independently. Poll `lb_sink_orders` after each write to observe delivery.

```elixir
# INSERT 3 orders.
for {id, item, qty} <- [{1, "widget", 9}, {2, "gadget", 4}, {3, "gizmo", 7}] do
  Postgrex.query!(sql, "INSERT INTO lb_orders (id, item, qty, memo) VALUES ($1, $2, $3, $4)", [
    id,
    item,
    qty,
    "memo-#{id}"
  ])
end

LbDemo.wait_until(fn -> LbDemo.count(:lb_sql, "lb_sink_orders") == 3 end)

# UPDATE order 1.
Postgrex.query!(sql, "UPDATE lb_orders SET qty = 42 WHERE id = 1", [])
LbDemo.wait_until(fn -> LbDemo.rows(:lb_sql, "SELECT qty FROM lb_sink_orders WHERE id = 1") == [[42]] end)

# DELETE order 2.
Postgrex.query!(sql, "DELETE FROM lb_orders WHERE id = 2", [])
LbDemo.wait_until(fn -> LbDemo.count(:lb_sql, "lb_sink_orders") == 2 end)

Kino.DataTable.new(
  LbDemo.rows(:lb_sql, "SELECT id, item, qty FROM lb_sink_orders ORDER BY id")
  |> Enum.map(fn [id, item, qty] -> %{id: id, item: item, qty: qty} end)
)
```

Inspect the captured `Replicant.Change` structs in delivery order. Under the
default replica identity, the delete carries the primary key in `old_record`.

```elixir
LbCapture.all()
|> List.flatten()
|> Enum.map(fn ch ->
  %{
    op: ch.op,
    table: ch.table,
    record: inspect(ch.record),
    old_record: inspect(ch.old_record),
    unchanged: inspect(ch.unchanged)
  }
end)
|> Kino.DataTable.new()
```

## Inspect cast row values

Add a table to the same publication, stream one row and inspect its nested
arrays, money value and time with offset. See
[ADR-0008](../../docs/adr/0008-casting-lenient-value-preserving-fallback.md) for
the choices behind those casts.

```elixir
cast_ddl = [
  "DROP TABLE IF EXISTS lb_cast",
  "CREATE TABLE lb_cast (id int PRIMARY KEY, grid numeric[], flags boolean[], moments timestamptz[], price money, at timetz)",
  "ALTER PUBLICATION lb_pub ADD TABLE lb_cast"
]

for stmt <- cast_ddl, do: Postgrex.query!(sql, stmt, [])

LbCapture.reset()

Postgrex.query!(
  sql,
  # NOTE: the money and timetz values are inlined SQL literals — Postgrex's
  # DefaultTypes has no `money` encoder and its `timetz` encoder wants a %Time{}
  # (lossy), so neither can ride as a bound parameter. (Replicant's own CDC path
  # never goes through Postgrex types: pgoutput delivers text that replicant casts
  # itself — that is exactly what this section demonstrates.)
  "INSERT INTO lb_cast (id, grid, flags, moments, price, at) VALUES ($1, $2, $3, $4, 1234.56::money, '04:05:06.789-08'::timetz)",
  [
    100,
    [[Decimal.new("1.5"), Decimal.new(2)], [Decimal.new(3), nil]],
    [[true, false]],
    [
      [~U[2024-01-15 10:30:00Z], ~U[2024-06-01 12:00:00Z]]
    ]
  ]
)

# The change arrives through the SAME pipeline (lb_cast is now in lb_pub).
LbDemo.wait_until(fn ->
  LbCapture.all() |> List.flatten() |> Enum.any?(& &1.record["grid"])
end)

cast_change =
  LbCapture.all()
  |> List.flatten()
  |> Enum.find(& &1.record["grid"])

%{
  grid_numeric_2d: inspect(cast_change.record["grid"]),
  flags_2d: inspect(cast_change.record["flags"]),
  moments_tz: inspect(cast_change.record["moments"]),
  price_money: inspect(cast_change.record["price"]),
  at_timetz: inspect(cast_change.record["at"])
}
```

What you just proved, on the live server:

```elixir
multidim_numeric = cast_change.record["grid"]
multidim_bool = cast_change.record["flags"]
tz_nested = cast_change.record["moments"]
money_value = cast_change.record["price"]
timetz_raw = cast_change.record["at"]

%{
  numeric_2d_nests_with_nil:
    multidim_numeric == [[Decimal.new("1.5"), Decimal.new(2)], [Decimal.new(3), nil]],
  bool_2d_casts: multidim_bool == [[true, false]],
  timestamptz_2d_casts: match?([[%DateTime{}, %DateTime{}]], tz_nested),
  # C/en-US lc_monetary renders "$1,234.56" -> Decimal; any other locale
  # honestly delivers the ORIGINAL string (never a silently-wrong Decimal).
  money_is_decimal_or_raw_string:
    is_struct(money_value, Decimal) or is_binary(money_value),
  # No Elixir type carries a time WITH its offset - the raw string keeps the
  # fractional seconds and the offset instead of truncating them.
  timetz_keeps_fraction_and_offset: timetz_raw == "04:05:06.789-08"
}
```

## Observe an unchanged TOAST column

Insert a large `memo`, then update only `qty`. The update lists `memo` in its
`unchanged` field, which tells the sink to preserve the stored value.

```elixir
big_memo = String.duplicate("x", 8_000)

Postgrex.query!(sql, "INSERT INTO lb_orders (id, item, qty, memo) VALUES (10, 'bulky', 1, $1)", [
  big_memo
])

LbDemo.wait_until(fn -> LbDemo.count(:lb_sql, "lb_sink_orders") == 3 end)

# Now update a DIFFERENT column and watch `memo` come through as unchanged.
LbCapture.reset()
Postgrex.query!(sql, "UPDATE lb_orders SET qty = 99 WHERE id = 10", [])
LbDemo.wait_until(fn -> LbCapture.any?() end)

toast_change =
  LbCapture.all()
  |> List.flatten()
  |> Enum.find(fn ch -> ch.op == :update and ch.record["id"] == 10 end)

toast_unchanged = toast_change.unchanged
```

The UPDATE produces `toast_unchanged == ["memo"]`. The 8 KB value does not
travel with the update.

## Inspect the transaction ledger

Read the append-only `lb_sink_calls` ledger. A repeated LSN among the applied
transactions indicates a duplicate effect. This query counts those repeats
and returns the mirror's IDs.

```elixir
calls =
  LbDemo.rows(:lb_sql, "SELECT lsn, outcome FROM lb_sink_calls ORDER BY seq")
  |> Enum.map(fn [lsn, outcome] -> {lsn, outcome} end)

applied_lsns = for {lsn, "applied"} <- calls, do: lsn
core_dup_count = length(applied_lsns) - length(Enum.uniq(applied_lsns))

{:ok, checkpoint_lsn} = LbCoreSink.checkpoint()
core_final_ids = LbDemo.ids(:lb_sql, "lb_sink_orders")

%{
  checkpoint: Replicant.lsn_to_string(checkpoint_lsn),
  applied_transactions: length(applied_lsns),
  duplicates: core_dup_count,
  mirror_ids: core_final_ids
}
```

Stop the pipeline before starting the snapshot exercise.

```elixir
LbDemo.stop(core_slot)
:core_stopped
```

## Backfill existing rows

Start with `snapshot: true` to mirror a table that already contains rows. This
sink implements the [point-in-time callbacks](../topics/delivery/snapshot-coverage.md#start-modes).
The snapshot completion callback commits the handoff checkpoint.

```elixir
defmodule LbSnapshotSink do
  @moduledoc false
  @behaviour Replicant.Sink

  alias Replicant.{Change, Transaction}

  @conn :lb_sql

  @impl true
  def checkpoint do
    case Postgrex.query(@conn, "SELECT lsn FROM lb_snapshot_cp WHERE id = 1", []) do
      {:ok, %Postgrex.Result{rows: [[lsn]]}} -> {:ok, lsn}
      {:ok, %Postgrex.Result{rows: []}} -> {:ok, nil}
      {:error, _} = err -> err
    end
  end

  @impl true
  def handle_snapshot(changes, %{first_for_table?: first?}) do
    Postgrex.transaction(@conn, fn c ->
      # Redo-safety: clear the prior snapshot-origin rows on the first batch per table.
      if first?, do: Postgrex.query!(c, "TRUNCATE lb_snapshot_sink", [])

      Enum.each(changes, fn %Change{record: r} ->
        Postgrex.query!(
          c,
          "INSERT INTO lb_snapshot_sink (id, name) VALUES ($1, $2) " <>
            "ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name",
          [r["id"], r["name"]]
        )
      end)
    end)

    :ok
  rescue
    e -> {:error, e}
  end

  @impl true
  def handle_snapshot_complete(lsn) do
    Postgrex.query!(
      @conn,
      "INSERT INTO lb_snapshot_cp (id, lsn) VALUES (1, $1) ON CONFLICT (id) DO UPDATE SET lsn = EXCLUDED.lsn",
      [lsn]
    )

    {:ok, lsn}
  end

  @impl true
  def handle_transaction(%Transaction{commit_lsn: lsn, changes: changes}) do
    Postgrex.transaction(@conn, fn c ->
      Enum.each(changes, fn
        %Change{op: op, record: r} when op in [:insert, :update] ->
          Postgrex.query!(
            c,
            "INSERT INTO lb_snapshot_sink (id, name) VALUES ($1, $2) " <>
              "ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name",
            [r["id"], r["name"]]
          )

        %Change{op: :delete, old_record: old} ->
          Postgrex.query!(c, "DELETE FROM lb_snapshot_sink WHERE id = $1", [old["id"]])

        _other ->
          :ok
      end)

      Postgrex.query!(
        c,
        "INSERT INTO lb_snapshot_cp (id, lsn) VALUES (1, $1) ON CONFLICT (id) DO UPDATE SET lsn = EXCLUDED.lsn",
        [lsn]
      )
    end)

    {:ok, lsn}
  end
end
```

Seed five rows into a fresh source table, then start with `snapshot: true` and
watch them arrive through `handle_snapshot/2`:

```elixir
snapshot_ddl = [
  "DROP PUBLICATION IF EXISTS lb_snapshot_pub",
  "DROP TABLE IF EXISTS lb_snapshot_orders, lb_snapshot_sink, lb_snapshot_cp",
  "CREATE TABLE lb_snapshot_orders (id int PRIMARY KEY, name text)",
  "CREATE TABLE lb_snapshot_sink (id int PRIMARY KEY, name text)",
  "CREATE TABLE lb_snapshot_cp (id int PRIMARY KEY, lsn bigint)",
  "CREATE PUBLICATION lb_snapshot_pub FOR TABLE lb_snapshot_orders"
]

for stmt <- snapshot_ddl, do: Postgrex.query!(sql, stmt, [])

for id <- 1..5 do
  Postgrex.query!(sql, "INSERT INTO lb_snapshot_orders (id, name) VALUES ($1, $2)", [
    id,
    "item-#{id}"
  ])
end

snapshot_slot = "replicant_lb_snapshot"

{:ok, _} =
  LbDemo.start_pipeline(
    connection: pg_opts,
    slot_name: snapshot_slot,
    publication: "lb_snapshot_pub",
    sink: LbSnapshotSink,
    snapshot: true
  )

LbDemo.wait_until(fn -> LbDemo.count(:lb_sql, "lb_snapshot_sink") == 5 end, 400)
snapshot_mirror_count = LbDemo.count(:lb_sql, "lb_snapshot_sink")
```

The five pre-existing rows were backfilled, and the pipeline is now streaming any
new commits from the snapshot's consistent point onward. Stop it:

```elixir
LbDemo.stop(snapshot_slot)
:snapshot_stopped
```

## Compare snapshot and stream coverage

Create a publication with a column list and row filter. `LbParitySink` stores
the snapshot and streamed changes in `LbCapture` so you can compare the
delivered record keys and rows with the publication.

```elixir
defmodule LbParitySink do
  @moduledoc false
  @behaviour Replicant.Sink

  alias Replicant.{Change, Transaction}

  @conn :lb_sql

  @impl true
  def checkpoint do
    case Postgrex.query(@conn, "SELECT lsn FROM lb_parity_cp WHERE id = 1", []) do
      {:ok, %Postgrex.Result{rows: [[lsn]]}} -> {:ok, lsn}
      {:ok, %Postgrex.Result{rows: []}} -> {:ok, nil}
      {:error, _} = err -> err
    end
  end

  @impl true
  def handle_snapshot(changes, %{first_for_table?: first?}) do
    Postgrex.transaction(@conn, fn c ->
      if first?, do: Postgrex.query!(c, "TRUNCATE lb_parity_sink", [])
      Enum.each(changes, &upsert(c, &1))
    end)

    LbCapture.record(changes)
    :ok
  rescue
    e -> {:error, e}
  end

  @impl true
  def handle_snapshot_complete(lsn) do
    set_cp(@conn, lsn)
    {:ok, lsn}
  end

  @impl true
  def handle_transaction(%Transaction{commit_lsn: lsn, changes: changes}) do
    change_list = Enum.to_list(changes)

    Postgrex.transaction(@conn, fn c ->
      case Postgrex.query!(c, "SELECT lsn FROM lb_parity_cp WHERE id = 1", []).rows do
        [[cp]] when is_integer(cp) and lsn <= cp ->
          :skipped

        _not_yet_applied ->
          Enum.each(change_list, &upsert(c, &1))
          set_cp(c, lsn)
      end
    end)

    LbCapture.record(change_list)
    {:ok, lsn}
  end

  # Snapshot rows and inserts/updates share one upsert; only the published columns exist.
  defp upsert(c, %Change{op: op, record: r}) when op in [:snapshot, :insert, :update] do
    Postgrex.query!(
      c,
      "INSERT INTO lb_parity_sink (id, item, qty) VALUES ($1, $2, $3) " <>
        "ON CONFLICT (id) DO UPDATE SET item = EXCLUDED.item, qty = EXCLUDED.qty",
      [r["id"], r["item"], r["qty"]]
    )
  end

  defp upsert(c, %Change{op: :delete, old_record: old}) do
    Postgrex.query!(c, "DELETE FROM lb_parity_sink WHERE id = $1", [old["id"]])
  end

  defp upsert(_c, _other), do: :ok

  defp set_cp(c, lsn) do
    Postgrex.query!(
      c,
      "INSERT INTO lb_parity_cp (id, lsn) VALUES (1, $1) ON CONFLICT (id) DO UPDATE SET lsn = EXCLUDED.lsn",
      [lsn]
    )
  end
end
```

The source table has four columns; the publication publishes three of them
(`internal_note` stays private) and only rows with a positive quantity. Five rows are
seeded, two of them with `qty = 0`, and the pipeline starts with `snapshot: true`:

```elixir
parity_ddl = [
  "DROP PUBLICATION IF EXISTS lb_parity_pub",
  "DROP TABLE IF EXISTS lb_parity_orders, lb_parity_sink, lb_parity_cp",
  "CREATE TABLE lb_parity_orders (id int PRIMARY KEY, item text, qty int, internal_note text)",
  "CREATE TABLE lb_parity_sink (id int PRIMARY KEY, item text, qty int)",
  "CREATE TABLE lb_parity_cp (id int PRIMARY KEY, lsn bigint)",
  # A column list (three of the four columns) AND a row filter (positive quantities only).
  "CREATE PUBLICATION lb_parity_pub FOR TABLE lb_parity_orders (id, item, qty) WHERE (qty > 0)"
]

for stmt <- parity_ddl, do: Postgrex.query!(sql, stmt, [])

seed = [{1, "widget", 3}, {2, "gadget", 0}, {3, "gizmo", 8}, {4, "doohickey", 0}, {5, "sprocket", 1}]

for {id, item, qty} <- seed do
  Postgrex.query!(
    sql,
    "INSERT INTO lb_parity_orders (id, item, qty, internal_note) VALUES ($1, $2, $3, $4)",
    [id, item, qty, "cost-basis-#{id}"]
  )
end

LbCapture.reset()
parity_slot = "replicant_lb_parity"

{:ok, _} =
  LbDemo.start_pipeline(
    connection: pg_opts,
    slot_name: parity_slot,
    publication: "lb_parity_pub",
    sink: LbParitySink,
    snapshot: true
  )

# Three of the five seeded rows satisfy `qty > 0`.
LbDemo.wait_until(fn -> LbDemo.count(:lb_sql, "lb_parity_sink") == 3 end)

snapshot_changes = LbCapture.all() |> List.flatten() |> Enum.filter(&(&1.op == :snapshot))
parity_snapshot_ids = snapshot_changes |> Enum.map(& &1.record["id"]) |> Enum.sort()

parity_snapshot_columns =
  snapshot_changes |> Enum.flat_map(&Map.keys(&1.record)) |> Enum.uniq() |> Enum.sort()

%{snapshot_ids: parity_snapshot_ids, snapshot_columns: parity_snapshot_columns}
```

The snapshot delivered ids `[1, 3, 5]` with exactly the keys `["id", "item", "qty"]`:
no `internal_note`, no filtered row. Now the stream. We insert a filtered-out row
first and a published row second; deliveries arrive in commit order, so once id 7 is
in the mirror, id 6's absence is proof that the server applied the same filter to
the stream:

```elixir
Postgrex.query!(
  sql,
  "INSERT INTO lb_parity_orders (id, item, qty, internal_note) VALUES (6, 'spacer', 0, 'cost-basis-6')",
  []
)

Postgrex.query!(
  sql,
  "INSERT INTO lb_parity_orders (id, item, qty, internal_note) VALUES (7, 'flange', 2, 'cost-basis-7')",
  []
)

LbDemo.wait_until(fn -> LbDemo.rows(:lb_sql, "SELECT id FROM lb_parity_sink WHERE id = 7") == [[7]] end)

stream_changes = LbCapture.all() |> List.flatten() |> Enum.filter(&(&1.op == :insert))
parity_stream_ids = Enum.map(stream_changes, & &1.record["id"])

parity_stream_columns =
  stream_changes |> Enum.flat_map(&Map.keys(&1.record)) |> Enum.uniq() |> Enum.sort()

parity_mirror_ids = LbDemo.ids(:lb_sql, "lb_parity_sink")

%{
  stream_ids: parity_stream_ids,
  stream_columns: parity_stream_columns,
  mirror_ids: parity_mirror_ids,
  same_shape?: parity_stream_columns == parity_snapshot_columns
}
```

Snapshot and stream agree on columns and on rows. The same rule covers generated
columns (excluded on PostgreSQL 15 as pgoutput excludes them; PostgreSQL 16+
follow the publication's effective list), and an ambiguous projection, such as two
publications naming one table with different column lists, halts
`:snapshot_column_list_conflict` before a single row is read.

```elixir
LbDemo.stop(parity_slot)
:parity_stopped
```

## Receive logical-decoding messages

Use `pg_logical_emit_message` to emit a transactional message and a standalone
one. Enable `messages: true` and compare `Replicant.Transaction` delivery with
`c:Replicant.Sink.handle_message/2`. See
[message delivery guarantees](../topics/delivery/invariants.md#deduplicate-logical-messages-at-the-correct-boundary)
for the effect each callback can promise.

```elixir
defmodule LbMessageSink do
  @moduledoc false
  @behaviour Replicant.Sink

  alias Replicant.Transaction
  alias Replicant.Decoder.Messages.Message

  @conn :lb_sql

  @impl true
  def checkpoint do
    case Postgrex.query(@conn, "SELECT lsn FROM lb_msg_cp WHERE id = 1", []) do
      {:ok, %Postgrex.Result{rows: [[lsn]]}} -> {:ok, lsn}
      {:ok, %Postgrex.Result{rows: []}} -> {:ok, nil}
      {:error, _} = err -> err
    end
  end

  @impl true
  def handle_transaction(%Transaction{commit_lsn: lsn}) do
    Postgrex.query!(
      @conn,
      "INSERT INTO lb_msg_cp (id, lsn) VALUES (1, $1) ON CONFLICT (id) DO UPDATE SET lsn = EXCLUDED.lsn",
      [lsn]
    )

    {:ok, lsn}
  end

  @impl true
  def handle_message(%Message{lsn: lsn, prefix: prefix, content: content}, %{lsn: ctx_lsn}) do
    # `prefix`/`content` are USER BYTES — Critical Rule 1 says never log or surface them
    # in telemetry. Persisting them into your own store (as here) is fine.
    Postgrex.query!(@conn, "INSERT INTO lb_msg_messages (lsn, prefix, content) VALUES ($1, $2, $3)", [
      ctx_lsn || lsn,
      prefix,
      content
    ])

    :ok
  end
end
```

```elixir
message_ddl = [
  "DROP PUBLICATION IF EXISTS lb_msg_pub",
  "DROP TABLE IF EXISTS lb_msg_orders, lb_msg_messages, lb_msg_cp",
  "CREATE TABLE lb_msg_orders (id int PRIMARY KEY, note text)",
  "CREATE TABLE lb_msg_messages (lsn bigint, prefix text, content text)",
  "CREATE TABLE lb_msg_cp (id int PRIMARY KEY, lsn bigint)",
  "CREATE PUBLICATION lb_msg_pub FOR TABLE lb_msg_orders"
]

for stmt <- message_ddl, do: Postgrex.query!(sql, stmt, [])

message_slot = "replicant_lb_messages"

{:ok, _} =
  LbDemo.start_pipeline(
    connection: pg_opts,
    slot_name: message_slot,
    publication: "lb_msg_pub",
    sink: LbMessageSink,
    messages: true,
    go_forward_only: true
  )

# Emit a non-transactional message straight into the WAL.
Postgrex.query!(sql, "SELECT pg_logical_emit_message(false, 'lb_heartbeat', 'tick')", [])
LbDemo.wait_until(fn -> LbDemo.count(:lb_sql, "lb_msg_messages") == 1 end)

nontxn_message =
  LbDemo.rows(:lb_sql, "SELECT prefix, content FROM lb_msg_messages")
  |> Enum.map(fn [prefix, content] -> {prefix, content} end)
  |> List.first()
```

```elixir
LbDemo.stop(message_slot)
:messages_stopped
```

## Explore other delivery modes

See [delivery guarantees](../topics/delivery/invariants.md) for batching, disk
spill and append-log delivery. The [source decoder guide](../topics/about/decoders.md)
covers multi-publication streams and pglogical. The [recovery guide](../how-to/recover.md)
explains halt signals and the separate retry budgets.

See the [pipeline options](https://hexdocs.pm/replicant/Replicant.html#start_link/1-options)
for the intake watermarks. Use `:paused` and `:resumed` to observe queue
pressure, and `:stalled` to detect a sink that stops completing work. See
[upgrade and monitoring](../how-to/upgrade.md#migrate-backpressure-alerts) for
WAL retention settings.

Set `receive_timeout` when starting a pipeline to enable recovery from
receive silence. The `:health` event marks a probe, `:receive_timeout`
marks a timed-out stream, and `:slot_release_wait` reports that another
backend still holds the slot. See
[recover a silent stream](../how-to/recover.md#recover-a-silent-stream)
for how the server timeout affects recovery.

## Verify delivery

Run the final cell to check the mirror, checkpoint, projected rows and
logical messages against the expected values.

```elixir
import ExUnit.Assertions

assert core_final_ids == [1, 3, 10]
assert core_dup_count == 0
assert toast_unchanged == ["memo"]
assert snapshot_mirror_count == 5
assert nontxn_message == {"lb_heartbeat", "tick"}

# Snapshot equals stream (1.5): only the published columns, only the filtered rows,
# identically by both paths.
assert parity_snapshot_ids == [1, 3, 5]
assert parity_snapshot_columns == ["id", "item", "qty"]
assert parity_stream_ids == [7]
assert parity_stream_columns == ["id", "item", "qty"]
assert parity_mirror_ids == [1, 3, 5, 7]

assert multidim_numeric == [[Decimal.new("1.5"), Decimal.new(2)], [Decimal.new(3), nil]]
assert multidim_bool == [[true, false]]
assert [[%DateTime{}, %DateTime{}]] = tz_nested
# The value 1234.56 renders "$1,234.56" (grouped) or "$1234.56" (C) — both parse
# to the same Decimal; a non-C lc_monetary form delivers the raw string instead.
assert Decimal.equal?(money_value, Decimal.new("1234.56"))
assert timetz_raw == "04:05:06.789-08"

:all_green
```

```elixir
%{
  core_final_ids: core_final_ids,
  core_dup_count: core_dup_count,
  toast_unchanged: toast_unchanged,
  snapshot_mirror_count: snapshot_mirror_count,
  parity_snapshot_ids: parity_snapshot_ids,
  parity_snapshot_columns: parity_snapshot_columns,
  parity_stream_ids: parity_stream_ids,
  parity_stream_columns: parity_stream_columns,
  parity_mirror_ids: parity_mirror_ids,
  nontxn_message: nontxn_message,
  multidim_numeric: multidim_numeric,
  multidim_bool: multidim_bool,
  tz_nested: tz_nested,
  money_value: money_value,
  timetz_raw: timetz_raw
}
```
