Report
Subscriber crash right after two_phase becomes enabled leaves the slot in two_phase mode with the subscription back to pending, silently losing rows of prepared transactions while tables are synchronized again
- Severity
- 80
- Blamed commit
- a8fd13cab0ba815e9925dc9676e6309f699b5f72
On 6 branches
REL_15_STABLE, REL_16_STABLE, REL_17_STABLE, REL_18_STABLE, REL_19_STABLE, master
Summary
When the last table of a subscription created with two_phase = on
reaches the READY state, the apply worker restarts, sends
START_REPLICATION with the two_phase option, and only then records the
ENABLED tri-state in pg_subscription. The publisher turns two_phase
into a durable property of the slot at once and keeps it for every
later START_REPLICATION, whether or not the option is given again. The
subscriber's half of the switch, the READY states and the ENABLED
update, consists of ordinary commits made under the subscription's
synchronous_commit setting, whose default is off.
A subscriber crash within the WAL writer's flush interval after the switch therefore loses those commits while the slot keeps two_phase. After recovery the subscription is PENDING again and the affected tables are synchronized from scratch, while the publisher already sends prepared transactions. The apply worker applies such a transaction with the rows of every not-yet-READY table skipped; the table synchronization worker cannot see them either, because its slot has no two_phase and the transaction is not committed yet; and COMMIT PREPARED later commits the incomplete transaction. Nothing is logged. The subscriber silently lacks rows that the publisher has.
Reproduced on master at 7fc2f0423320e02beb8c44b863f1827604c47c75 and on REL_15_STABLE. The same reverted state also reopens both problems fixed by fc1900915b1 for the ALTER SUBSCRIPTION path (disabling two_phase with prepared transactions present, and REFRESH PUBLICATION with copy_data while the slot decodes two-phase), because the checks there assume that a two_phase slot implies the ENABLED state.
Reproduction
Two instances. Publisher: wal_level = logical,
max_prepared_transactions = 10. Subscriber:
max_prepared_transactions = 10, wal_writer_delay = 10s,
wal_writer_flush_after = 1GB. The last two only widen the crash
window from the default 200 ms to 10 s so that it can be hit by hand;
the WAL writer is otherwise only woken when more than
wal_writer_flush_after of WAL is pending (XLogSetAsyncXactLSN), which
tiny commits never reach.
Publisher:
CREATE TABLE t1 (a int PRIMARY KEY);
CREATE TABLE t2 (a int PRIMARY KEY);
INSERT INTO t2 SELECT generate_series(1, 1000);
CREATE PUBLICATION pub FOR TABLE t1, t2;
Subscriber. The ALWAYS trigger only exists to hold the copy of t2 open deterministically during the second synchronization, i.e. after a postmaster restart; it lets the first synchronization run freely. Logical replication workers run with an empty search_path, hence the schema qualification.
CREATE TABLE t1 (a int PRIMARY KEY);
CREATE TABLE t2 (a int PRIMARY KEY);
CREATE TABLE ctl (start timestamptz, go bool);
INSERT INTO ctl SELECT pg_postmaster_start_time(), false;
CREATE FUNCTION t2_gate() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF (SELECT start FROM public.ctl) <> pg_postmaster_start_time() THEN
LOOP
EXIT WHEN (SELECT go FROM public.ctl);
PERFORM pg_sleep(0.05);
END LOOP;
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER t2_gate BEFORE INSERT ON t2
FOR EACH ROW EXECUTE FUNCTION t2_gate();
ALTER TABLE t2 ENABLE ALWAYS TRIGGER t2_gate;
CREATE SUBSCRIPTION sub CONNECTION '<publisher connstr>'
PUBLICATION pub WITH (two_phase = true);
Then, in a shell, poll the subscriber until the switch is visible and crash it at once:
while [ "$(psql -Atq -c "SELECT subtwophasestate FROM pg_subscription")" != e ]; do :; done
pg_ctl -D $PGDATA stop -m immediate # ~0.1 s after seeing 'e'
pg_ctl -D $PGDATA start -w
State after crash recovery (publisher slot, then subscriber):
slot_name | two_phase | two_phase_at IS NOT NULL
sub | t | t
subname | subtwophasestate
sub | p
srrelid | srsubstate
t1 | d
t2 | d
Wait until the table synchronization worker for t2 is blocked in the
gate (pg_stat_activity shows it in wait_event PgSleep) and t1 is
READY again, then on the publisher:
BEGIN;
INSERT INTO t1 VALUES (-7);
INSERT INTO t2 VALUES (-7);
PREPARE TRANSACTION 'p2';
The subscriber, still PENDING, applies it as a prepared transaction
(SELECT count(*) FROM pg_prepared_xacts returns 1). Release the gate
with UPDATE ctl SET go = true, wait until both tables are r and
the subscription is e again, then on the publisher:
COMMIT PREPARED 'p2';
Expected: both sides agree. Actual (publisher first):
publisher : t1=1 t2=1001 t1 has -7: t t2 has -7: t
subscriber: t1=1 t2=1000 t1 has -7: t t2 has -7: f
subscriber errors in log: 0
The row for t2 is gone for good; the subscriber log contains no ERROR
or WARNING. With the fix below, the same script finds e and both
tables r after recovery, and the prepared transaction arrives whole
(1 and 1001 rows on both sides).
Analysis
run_apply_worker() in src/backend/replication/logical/worker.c:
if (MySubscription->twophasestate == LOGICALREP_TWOPHASE_STATE_PENDING &&
AllTablesyncsReady())
{
/* Start streaming with two_phase enabled */
options.proto.logical.twophase = true;
walrcv_startstreaming(LogRepWorkerWalRcvConn, &options);
StartTransactionCommand();
...
UpdateTwoPhaseState(MySubscription->oid, LOGICALREP_TWOPHASE_STATE_ENABLED);
MySubscription->twophasestate = LOGICALREP_TWOPHASE_STATE_ENABLED;
PopActiveSnapshot();
CommitTransactionCommand();
}
The worker has set synchronous_commit from subsynccommit
(SetConfigOption("synchronous_commit", MySubscription->synccommit, ...)), and CREATE SUBSCRIPTION stores off unless told otherwise
(src/backend/commands/subscriptioncmds.c: "The default for
synchronous_commit of subscriptions is off"). So the commit above is
asynchronous: visible at once, on disk only when the WAL writer gets
to it.
On the publisher, CreateDecodingContext() in
src/backend/replication/logical/logical.c reacts to the option
immediately and durably:
ctx->twophase &= (slot->data.two_phase || ctx->twophase_opt_given);
/* Mark slot to allow two_phase decoding if not already marked */
if (ctx->twophase && !slot->data.two_phase)
{
...
slot->data.two_phase = true;
slot->data.two_phase_at = start_lsn;
...
ReplicationSlotMarkDirty();
ReplicationSlotSave();
and pgoutput_startup() in
src/backend/replication/pgoutput/pgoutput.c documents the asymmetry:
the option "remains enabled if the previous start-up has done so".
set_stream_options() in worker.c always passes twophase = false;
an ENABLED subscription relies on the slot flag alone, and a PENDING
one has no way to ask the publisher to stop.
The READY side has the same weakness. ProcessSyncingTablesForApply()
in src/backend/replication/logical/tablesync.c marks the last table
READY, notices in the same transaction that all tables are ready,
commits (asynchronously, same GUC), and proc_exit(0)s so that the
restarted worker can do the switch above. The SYNCDONE and
FINISHEDCOPY commits of the table synchronization workers are
asynchronous as well.
So after a crash, recovery stops at the WAL writer's last flush: the ENABLED update, the READY updates, the sync workers' progress and the replication origin's position are all rolled back, while the slot on the publisher is two_phase. The restarted apply worker finds PENDING with tables not READY, so it starts streaming without the two_phase option, which the publisher ignores, and launches synchronization workers. Then:
apply_handle_begin_prepare()/apply_handle_prepare()accept the PREPARE without checking the tri-state; the design comment atop worker.c ("the subscription will behave as if two_phase = off" until ENABLED) is not enforced anywhere on the receiving side.should_apply_changes_for_rel()returns false for a table in INIT/DATASYNC/FINISHEDCOPY, so the prepared transaction is prepared locally without that table's rows.- The table synchronization worker creates its slot without two_phase
(
walrcv_create_slot(..., false /* two_phase */, ...)), so the prepared transaction is invisible to it until COMMIT PREPARED, and its catch-up ends at the apply worker's position, which is before that. apply_handle_commit_prepared()commits the local prepared transaction as it is.
This is exactly the "empty prepare" scenario the comment atop worker.c describes and that the PENDING/ENABLED tri-state was introduced to rule out; the tri-state just was never made as durable as the slot flag it is supposed to mirror.
Window: with default settings the WAL writer flushes every 200 ms and
the READY-restart-ENABLED sequence takes roughly 100-300 ms, so any
subscriber crash (power loss, OOM kill, immediate shutdown) in the
200 ms around a two_phase switch produces the state. The switch
happens once per subscription creation, after ALTER SUBSCRIPTION ...
SET (two_phase = true) and ENABLE, and after a REFRESH PUBLICATION
that added tables while PENDING. Once in the state, the exposure
lasts for the whole re-synchronization of the reverted tables, which
for large tables is minutes to hours, and every prepared transaction
touching them during that time loses rows on the subscriber. Setting
synchronous_commit = on for the subscription avoids the problem,
but that is neither the default nor documented as a requirement.
The behavior dates from a8fd13cab0ba815e9925dc9676e6309f699b5f72 ("Add support for prepared transactions to built-in logical replication", 2021-07-14), which added the tri-state, the walrcv_startstreaming-then-UpdateTwoPhaseState order, the slot-side persistence in CreateDecodingContext and the "remains enabled" rule in pgoutput; the two_phase block has only been moved (02c1b64fb15c) and given a snapshot (706054b11b95) since.
Affected branches
master and REL_19_STABLE through REL_15_STABLE, all of which contain a8fd13cab0b. REL_14_STABLE has two-phase decoding but no subscription two_phase option and is not affected.
Verified by crashing the subscriber right after the switch and
restarting it with max_logical_replication_workers = 0, so that the
catalog shows what recovery left: on unpatched master and unpatched
REL_15_STABLE the subscription is p and two tables are not READY;
with the fix it is e and all tables are READY.
Fix
Make the subscriber's half of the switch as durable as the slot flag
it mirrors, independent of the subscription's synchronous_commit.
ForceSyncCommit() is the existing primitive for commits that must
not be lost once visible (CREATE DATABASE, tablespaces); it flushes
the commit record before the transaction becomes visible, so
observing e or r implies they are on disk. Two call sites:
ProcessSyncingTablesForApply(): in the transaction that marks the last table READY and decides to restart for two_phase. Flushing that commit also flushes every earlier SYNCDONE/READY commit.run_apply_worker(): in the transaction that records ENABLED.
With both, a crash between START_REPLICATION and the ENABLED commit
leaves the slot two_phase and the subscription PENDING but all tables
durably READY, and the restarted worker re-enables two_phase before
reading any data, so no prepared transaction can be applied or lost in
between. The REL_15 version of the tablesync function detects the
all-READY condition at the start of a later call and exits directly,
so the back-branch patch flushes the READY commit made by the same
worker earlier with XLogFlush(XactLastCommitEnd) instead. The patch
also extends src/test/subscription/t/021_twophase.pl with a crash
right after the switch; the new assertions fail on unpatched code and
pass with the fix.
Risk: two one-time synchronous commits per subscription, no catalog, protocol or behavior change otherwise; back-patchable to 15.
Alternatives considered and not taken:
- Commit ENABLED before START_REPLICATION. A crash between the two
would then leave ENABLED with a slot that is not two_phase, and
set_stream_options()never asks for two_phase, so it would stay that way; fixing that means passing the option whenever ENABLED, which changes the replacement-slot behavior that fc1900915b1 deliberately kept. - Reject BEGIN PREPARE while PENDING in the apply worker (the detection approach proposed in the second thread below). That turns the silent loss into a repeating ERROR but cannot resolve the state, since a PENDING subscription cannot turn the slot's two_phase off without breaking prepared transactions it may already hold. It is a useful safety net on top of this fix, not a replacement.
Testing
- master (7fc2f042332): the two_phase TAP tests
(subscription/021, 022, 023) pass with the patch; the new section of
021 fails on unpatched code (
got: 'p', 2 tables not READY). - REL_19_STABLE (5c839a2a08b): patch applies as is; 021 passes.
- REL_15_STABLE (41754dd1196): adjusted patch; 021 passes; the new section fails on unpatched code the same way.
- The hand reproduction above, run against the patched master
binaries, shows
eand both tablesrafter recovery and the prepared transaction replicated whole.
Prior discussion
- 8e85abdf-738b-4578-ac42-4dc8eaa061dd@gmail.com, "Avoid resetting subscription two_phase state to pending when already enabled" (2026-10-29, leading to fc1900915b1). Reaches the same inconsistent state through ALTER SUBSCRIPTION ... SET (two_phase = true) on an ENABLED subscription and describes the same consequences (empty prepares during initial sync, self-deadlocks after disabling two_phase). Neither a crash nor the durability of the catalog update is discussed; the crash path remains open after that commit.
- avMmtxMsgqKy4IQq@bdtpg, "Detect mismatched subscription and replication slot properties" (2026-11-10). Proposes validating the slot's two_phase and failover flags against the subscription state when the apply worker starts, or rejecting prepared transactions while PENDING, and notes that accepting either flag while PENDING "also makes the transition safe if the worker previously exited between those two operations". No cause other than user action is named and no patch is attached. This report supplies a cause that needs no user action, shows the resulting data loss, and fixes the cause rather than detecting the result.