Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
7eb4c25
sql: add CREATE SINK ... INTO POSTGRES
patrickwwbutler Oct 9, 2026
95c25ca
storage-types: drop the Postgres sink staging table name
patrickwwbutler Nov 13, 2026
216701f
doc: add a design doc for Postgres sinks
patrickwwbutler Nov 13, 2026
ed78b48
storage: render Postgres sinks and create their tables
patrickwwbutler Nov 13, 2026
22cc511
storage: stage Postgres sink updates with COPY
patrickwwbutler Nov 13, 2026
078bfa9
storage: apply staged Postgres sink updates to the target table
patrickwwbutler Nov 13, 2026
9a19bd0
test: add testdrive coverage for Postgres sinks
patrickwwbutler Oct 9, 2026
85075c5
test: update Postgres sink testdrive for the redesigned writer
patrickwwbutler Nov 13, 2026
e177634
test: move Postgres sink tests into their own composition
patrickwwbutler Nov 13, 2026
f9eb078
test: cover Postgres sinks on a multi-replica cluster
patrickwwbutler Nov 13, 2026
e1060ee
test: roundtrip Postgres sinks in the testdrive composition
def- Nov 17, 2026
ee58514
data-ingest: roundtrip generated data through Postgres sinks
def- Nov 17, 2026
1a0ca90
parallel-workload: exercise Postgres sinks
def- Nov 17, 2026
d461a8f
platform-checks: roundtrip Postgres sinks across disruptions
def- Nov 17, 2026
b503d6c
source-sink-errors: cover Postgres sink disruptions
def- Nov 17, 2026
312d28c
0dt: verify Postgres sink takeover and standby isolation
def- Nov 17, 2026
0bcf072
bounded-memory: exercise Postgres sink snapshots and recovery
def- Nov 17, 2026
fdbf627
zippy: roundtrip Postgres sinks from generated views
def- Nov 17, 2026
3aedf9c
test: roundtrip Postgres sinks over SSH and TLS and check secret logging
def- Nov 17, 2026
e3892c6
test: tighten Postgres sink roundtrip validation
def- Nov 17, 2026
23ea0c1
test: exercise the v1 upsert failpoint during zero-downtime deploys
def- Nov 17, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

138 changes: 138 additions & 0 deletions doc/developer/design/20261016_postgres_sink.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# Postgres sink

- Associated: [#39163](https://github.com/MaterializeInc/materialize/pull/39163)

## The problem

Users want a materialized view kept up to date in a PostgreSQL table, with
the same exactly-once guarantees the Kafka sink gives. The first cut of the
sink used three operators, a persistent staging table per sink, and
`pg_terminate_backend` to fence earlier incarnations. This document records
the simpler design that replaced it.

## Success criteria

- A `CREATE SINK ... INTO POSTGRES CONNECTION` keeps the target table equal to
the sinked relation, applying each Materialize timestamp exactly once across
restarts, replica changes and `ALTER SINK`.
- A superseded incarnation of the sink (a zombie replica, or two replicas
running by mistake) can never commit to the target.
- The sink leaves nothing in the target database beyond the target table and
one bookkeeping row.

## Solution proposal

The dataflow has two operators, matching the Kafka sink:

1. `encode` runs on every worker and turns each `(row, time, diff)` into a
`COPY ... BINARY` staging row (the source columns, `mz_timestamp`,
`mz_diff = ±1`). Encoding is the CPU-heavy part, so it is sharded.
2. `write` runs on one worker, chosen by hashing the sink id, and holds the
only connection to the target database.

The write operator is the whole protocol. At startup it:

- creates `materialize.sink_progress` and the target table if needed. The
sink's `KEY` becomes the primary key, so the per-window delete is an index
lookup. A key with a nullable column gets a plain index instead, and a
keyless sink's target gets neither.
- claims the sink's progress row: `UPDATE ... SET epoch = epoch + 1,
sink_version = $v WHERE sink_id = $id AND sink_version <= $v RETURNING
epoch, mz_frontier`. No row returned means a newer version of the sink owns
the table, and the operator halts.
- reconciles the persist progress shard with the recorded frontier. The row is
the source of truth because it moves in the same transaction as the data.
A shard behind the row is pulled forward. A shard ahead of the row means the
target lost committed writes, and the sink halts with that message.
- creates a session temporary table `mz_sink_stage ... ON COMMIT DELETE
ROWS`.

Then, for each window `[lower, upper)` the input frontier closes, in one
transaction:

```
BEGIN ISOLATION LEVEL SERIALIZABLE
SELECT epoch, mz_frontier FROM materialize.sink_progress WHERE sink_id = $id
-- halt unless epoch is ours and mz_frontier = lower
COPY pg_temp.mz_sink_stage FROM STDIN (FORMAT BINARY)
-- streamed as rows arrive; rows exactly at `lower` go straight in,
-- which is what streams a snapshot without buffering it
WITH latest AS (SELECT DISTINCT ON (key) ... FROM pg_temp.mz_sink_stage
ORDER BY key, mz_timestamp DESC, mz_diff DESC),
deleted AS (DELETE FROM target t USING latest l WHERE t.key = l.key),
inserted AS (INSERT INTO target SELECT ... FROM latest WHERE mz_diff > 0)
SELECT counts
UPDATE materialize.sink_progress SET mz_frontier = upper
WHERE sink_id = $id AND epoch = $epoch -- halt unless one row
COMMIT
```

A sink without a key replaces the `WITH latest ...` statement with an
`INSERT` of the staged insertions, then a `DELETE` of as many copies of each
retracted row as were retracted, picked out by `ctid`.

After the commit, and only then, the persist progress shard is advanced to
`upper`.

### Why this is correct

- **Exactly once.** A window is applied and its frontier recorded in one
transaction, so a crash leaves either both or neither. On restart the
recorded frontier is the resume point, and the as-of handling mirrors the
Kafka sink's: progress is only recorded once strictly beyond the as-of.
- **Fencing.** Every incarnation bumps the epoch before writing, and every
window checks the epoch at `BEGIN` and again in the final `UPDATE`. Under
`SERIALIZABLE` a zombie whose window straddles a newer claim fails at
commit, and a zombie that starts a window after the claim fails at
`BEGIN`. `sink_version` fences the same way across `ALTER SINK`, as the
Kafka and Iceberg sinks do.
- **Multiple timestamps per key in one window.** `DISTINCT ON` keeps the
latest event for each key, and at that timestamp the insertion over the
retraction, so an update lands as its new value and a delete as nothing.
Every touched key is deleted and the survivors reinserted. This is why a
key must be unique: with duplicates a key-matched retraction cannot say
which row to remove. The planner enforces it exactly as it does for Kafka
upsert sinks, `KEY (...)` must be a unique key of the relation unless
`NOT ENFORCED` is given.
- **Duplicates without a key.** A keyless target may hold identical rows, so
a retraction deletes exactly its count of matching rows by `ctid`, and the
window halts if fewer are found. The match is on every column and cannot
use an index, which is the cost of a sink without a key.
- **Nothing persistent to clean.** The staging table is session temporary.
A dropped connection drops it and rolls back the open window.

### Comparison with the other sinks

| | Kafka | Iceberg | Postgres |
| --- | --- | --- | --- |
| Encoding | all workers | all workers | all workers |
| Writing | one worker, transactional producer | all workers write files, one commits | one worker, one connection |
| Progress store | progress topic record | snapshot property | `materialize.sink_progress` row |
| Fence | producer epoch via `init_transactions` + `sink_version` | `sink_version` in snapshot | `epoch` + `sink_version` in progress row |
| Key required | yes for `ENVELOPE UPSERT` | yes for upsert mode | no |

The single writer bounds throughput by one connection's `COPY` rate, the
same bound the Kafka sink has on one producer. PostgreSQL executes a `COPY`
and the apply statement single-threaded, so a very large snapshot is
applied by one backend. Parallel writers would need per-writer temporary
tables and a two-phase commit, which is not worth it until a workload shows
the bound.

## Alternatives

- **Persistent staging table and a truncate on restart.** Needs
`pg_terminate_backend` to clear out a zombie's open `COPY` before the
truncate, and leaves a table and two indexes per sink in the user's schema.
- **Row locks instead of `SERIALIZABLE`.** `SELECT ... FOR UPDATE` on the
progress row gives the same compare-and-set and avoids serialization
failures from the user's own serializable transactions on the target table.
Kept as the fallback if those failures turn up in practice.
- **Requiring a key.** Would halve the apply logic and keep every retraction
an index lookup, but rejects relations that have no unique key and whose
users want duplicates kept.

## Open questions

- Whether to record progress on every input frontier advance (as now, and as
Kafka does) or on a `COMMIT INTERVAL` like Iceberg, to reduce write traffic
to the user's database when the sink is idle.
83 changes: 83 additions & 0 deletions misc/python/materialize/checks/all_checks/pg_sink.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Copyright Materialize, Inc. and contributors. All rights reserved.
#
# Use of this software is governed by the Business Source License
# included in the LICENSE file at the root of this repository.
#
# As of the Change Date specified in that file, in accordance with
# the Business Source License, use of this software will be governed
# by the Apache License, Version 2.0.

from textwrap import dedent

from materialize.checks.actions import Testdrive
from materialize.checks.checks import Check, externally_idempotent
from materialize.checks.executors import Executor
from materialize.mz_version import MzVersion


@externally_idempotent(False)
class PgSink(Check):
def _can_run(self, e: Executor) -> bool:
return self.base_version >= MzVersion.parse_mz("v26.52.0-dev")

def _roundtrip(self, phase: int) -> str:
return "".join(dedent(f"""
> CREATE SINK pg_sink_{kind}{phase} FROM pg_sink_{kind}
INTO POSTGRES CONNECTION pg_sink_conn (SCHEMA 'pgsink', TABLE '{kind}{phase}')
{"KEY (a) NOT ENFORCED" if kind == "keyed" else ""}

> SELECT write_frontier > 0 FROM mz_internal.mz_frontiers
WHERE object_id = (SELECT id FROM mz_sinks WHERE name = 'pg_sink_{kind}{phase}')
true

$ postgres-execute connection=postgres://postgres:postgres@postgres
ALTER TABLE pgsink.{kind}{phase} REPLICA IDENTITY FULL;
CREATE PUBLICATION pg_sink_{kind}{phase} FOR TABLE pgsink.{kind}{phase};

> CREATE SOURCE pg_sink_{kind}{phase}_source FROM POSTGRES CONNECTION pg_sink_conn
(PUBLICATION 'pg_sink_{kind}{phase}')
> CREATE TABLE pg_sink_{kind}{phase}_readback FROM SOURCE pg_sink_{kind}{phase}_source
(REFERENCE pgsink.{kind}{phase})

> SELECT * FROM
((SELECT * FROM pg_sink_{kind} EXCEPT ALL SELECT * FROM pg_sink_{kind}{phase}_readback)
UNION ALL
(SELECT * FROM pg_sink_{kind}{phase}_readback EXCEPT ALL SELECT * FROM pg_sink_{kind}))
""") for kind in ["keyed", "keyless"])

def initialize(self) -> Testdrive:
return Testdrive(dedent("""
$ postgres-execute connection=postgres://postgres:postgres@postgres
CREATE SCHEMA pgsink;

> CREATE SECRET pg_sink_pass AS 'postgres'
> CREATE CONNECTION pg_sink_conn TO POSTGRES
(HOST postgres, DATABASE postgres, USER postgres, PASSWORD SECRET pg_sink_pass)
> CREATE TABLE pg_sink_keyed (a int NOT NULL, b text)
> INSERT INTO pg_sink_keyed VALUES (1, 'dup'), (2, 'dup'), (3, 'dup'), (4, NULL)
> CREATE MATERIALIZED VIEW pg_sink_keyless AS SELECT b FROM pg_sink_keyed
""") + self._roundtrip(0))

def manipulate(self) -> list[Testdrive]:
return [Testdrive(dedent(f"""
> UPDATE pg_sink_keyed SET b = 'phase{phase}' WHERE a = 1
> DELETE FROM pg_sink_keyed WHERE a = {phase + 1}
> INSERT INTO pg_sink_keyed VALUES ({phase + 4}, 'dup')
""") + self._roundtrip(phase)) for phase in [1, 2]]

def validate(self) -> Testdrive:
return Testdrive(
dedent("""
> SELECT * FROM pg_sink_keyed
1 phase2
4 <null>
5 dup
6 dup
""")
+ "".join(dedent(f"""
> SELECT * FROM
((SELECT * FROM pg_sink_{kind} EXCEPT ALL SELECT * FROM pg_sink_{kind}{phase}_readback)
UNION ALL
(SELECT * FROM pg_sink_{kind}{phase}_readback EXCEPT ALL SELECT * FROM pg_sink_{kind}))
""") for phase in range(3) for kind in ["keyed", "keyless"])
)
95 changes: 95 additions & 0 deletions misc/python/materialize/data_ingest/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -891,6 +891,101 @@ def run(self, transaction: Transaction, logging_exe: Any | None = None) -> None:
self.pg_conn.commit()


class PgRoundtripExecutor(Executor):
def __init__(
self,
num: int,
ports: dict[str, int],
fields: list[Field],
database: str,
schema: str = "public",
cluster: str | None = None,
mz_service: str | None = None,
composition: Composition | None = None,
):
super().__init__(
ports, fields, database, schema, cluster, mz_service, composition
)
self.num = num
self.table = f"pg_roundtrip{num}"

def create(self, logging_exe: Any | None = None) -> None:
self.logging_exe = logging_exe
target = f"{self.table}_target"
source = f"{self.table}_source"
qualified_schema = f"{identifier(self.database)}.{identifier(self.schema)}"
keys = ", ".join(identifier(f.name) for f in self.fields if f.is_key)
key = f"KEY ({keys}) NOT ENFORCED" if random.choice([True, False]) else ""
with self.mz_conn.cursor() as cur:
self.execute(
cur,
f"""CREATE SINK {qualified_schema}.{self.table}_sink
{f"IN CLUSTER {identifier(self.cluster)}" if self.cluster else ""}
FROM {qualified_schema}.table{self.num}
INTO POSTGRES CONNECTION pg{self.num} (SCHEMA 'public', TABLE '{target}')
{key}""",
)

with psycopg.connect(
host="127.0.0.1",
user="postgres",
password="postgres",
port=self.ports["postgres"],
autocommit=True,
) as pg_conn:
with pg_conn.cursor() as cur:
self.execute_with_retry_on_error(
cur,
f"""ALTER TABLE {target} REPLICA IDENTITY FULL;
CREATE PUBLICATION {source} FOR TABLE {target}""",
required_error_message_substrs=["does not exist"],
max_tries=60,
)

with self.mz_conn.cursor() as cur:
self.execute(
cur,
f"""CREATE SOURCE {qualified_schema}.{source}
{f"IN CLUSTER {identifier(self.cluster)}" if self.cluster else ""}
FROM POSTGRES CONNECTION pg{self.num} (PUBLICATION '{source}')""",
)
self.execute(
cur,
f"""CREATE TABLE {qualified_schema}.{self.table}
FROM SOURCE {qualified_schema}.{source} (REFERENCE public.{target})""",
)

def run(self, transaction: Transaction, logging_exe: Any | None = None) -> None:
# PgExecutor supplies the input to this sink.
pass

def wait_for_sink(self, cur: psycopg.Cursor) -> None:
# An empty readback can match before the sink processes any input.
cur.execute(
"SELECT write_frontier FROM mz_internal.mz_frontiers "
"WHERE object_id = (SELECT id FROM mz_tables WHERE name = %s)",
(f"table{self.num}",),
)
row = cur.fetchone()
assert row is not None
frontier = row[0]
deadline = time.monotonic() + 60
while True:
cur.execute(
"SELECT write_frontier >= %s::mz_timestamp FROM mz_internal.mz_frontiers "
"WHERE object_id = (SELECT id FROM mz_sinks WHERE name = %s)",
(frontier, f"{self.table}_sink"),
)
row = cur.fetchone()
if row is not None and row[0]:
return
if time.monotonic() >= deadline:
raise TimeoutError(
f"{self.table}_sink did not reach frontier {frontier}"
)
time.sleep(0.1)


class KafkaRoundtripExecutor(Executor):
table: str
table_original: str
Expand Down
7 changes: 6 additions & 1 deletion misc/python/materialize/data_ingest/workload.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from materialize.data_ingest.executor import (
KafkaExecutor,
PgExecutor,
PgRoundtripExecutor,
PrintExecutor,
)
from materialize.data_ingest.field import Field
Expand Down Expand Up @@ -310,7 +311,9 @@ def execute_workload(
mz_service=workload.mz_service,
composition=composition,
cluster=(
"quickstart" if executor_class == KafkaExecutor else "singlereplica"
"quickstart"
if executor_class in (KafkaExecutor, PgRoundtripExecutor)
else "singlereplica"
),
)
for executor_class in [PgExecutor] + executor_classes
Expand Down Expand Up @@ -352,6 +355,8 @@ def execute_workload(
conn.autocommit = True
with conn.cursor() as cur:
try:
if isinstance(executor, PgRoundtripExecutor):
executor.wait_for_sink(cur)
cur.execute("SET REAL_TIME_RECENCY TO TRUE")
cur.execute(
f"SELECT * FROM {executor.table} ORDER BY {order_str}".encode()
Expand Down
Loading