配套源码:
~/cwork/postgresql(基于 PG 18 主干)预设场景:
- 发布端 PG 18,
wal_level=logical- 订阅选项
streaming='parallel'(PG 16+ 才有的并行 apply 模式)logical_decoding_work_mem='64kB'(极小,几乎每条变更都触发 stream)- 每个事务都通过流式协议发送(而非攒齐一次性发送)
本文聚焦 发布端 视角,详细拆解:
logical_decoding_work_mem=64kB究竟意味着什么、触发什么行为streaming='parallel'在发布端如何体现- 一个事务从 BEGIN → 多次 stream_chunk → COMMIT 的完整发送链路
stream_start/stream_stop/stream_commit/stream_abort/stream_change等协议消息的发送时机- pgoutput 输出插件在其中的角色
一、关键配置的真实含义
1.1 logical_decoding_work_mem='64kB' —— 内存墙被压到 64KB
源码位置:src/backend/utils/misc/guc_tables.c:2604,src/include/replication/reorderbuffer.h:27。
// src/backend/utils/misc/guc_tables.c:2613-2620
{"logical_decoding_work_mem", PGC_USERSET, RESOURCES_MEM,
gettext_noop("Sets the maximum memory to be used for logical decoding."),
gettext_noop("This much memory can be used by each internal "
"reorder buffer before spilling to disk."),
GUC_UNIT_KB
},
&logical_decoding_work_mem,
65536, 64, MAX_KILOBYTES,
默认值是 64MB,我们配成 64KB(小 1024 倍)。这并不是”减少内存使用”那么简单——它直接决定了 Reorder Buffer 何时触发 streaming。
1.2 streaming='parallel' —— 在发布端怎么体现?
源码位置:src/backend/replication/logical/worker.c:4455-4475(订阅端发起)。
// src/backend/replication/logical/worker.c:4499-4510
if (server_version >= 160000 &&
MySubscription->stream == LOGICALREP_STREAM_PARALLEL)
{
options->proto.logical.streaming_str = "parallel";
MyLogicalRepWorker->parallel_apply = true;
}
else if (server_version >= 140000 &&
MySubscription->stream != LOGICALREP_STREAM_OFF)
{
options->proto.logical.streaming_str = "on";
MyLogicalRepWorker->parallel_apply = false;
}
注意:streaming 是订阅端的订阅选项,但通过 logical replication protocol 传递给发布端,决定 pgoutput 插件输出哪些协议消息。
streaming='parallel' 在发布端意味着:
- pgoutput 注册了 6 个 stream callback(start/stop/change/commit/abort/prepare)
- ctx->streaming 被设为 true
- Reorder Buffer 的
ReorderBufferCanStream(rb)返回 true
源码 src/backend/replication/logical/logical.c:238:
// src/backend/replication/logical/logical.c:331-337
ctx->streaming = (ctx->callbacks.stream_start_cb != NULL) ||
(ctx->callbacks.stream_stop_cb != NULL) ||
(ctx->callbacks.stream_abort_cb != NULL) ||
(ctx->callbacks.stream_commit_cb != NULL) ||
(ctx->callbacks.stream_change_cb != NULL) ||
(ctx->callbacks.stream_message_cb != NULL) ||
(ctx->callbacks.stream_truncate_cb != NULL);
1.3 输出插件的 6 个 stream callback
源码位置:src/include/replication/output_plugin.h:235、src/backend/replication/pgoutput/pgoutput.c:278。
// src/backend/replication/pgoutput/pgoutput.c:261-287
_PG_output_plugin_init(OutputPluginCallbacks *cb)
{
cb->startup_cb = pgoutput_startup;
cb->begin_cb = pgoutput_begin_txn;
cb->change_cb = pgoutput_change;
cb->truncate_cb = pgoutput_truncate;
cb->message_cb = pgoutput_message;
cb->commit_cb = pgoutput_commit_txn;
cb->begin_prepare_cb = pgoutput_begin_prepare_txn;
cb->prepare_cb = pgoutput_prepare_txn;
cb->commit_prepared_cb = pgoutput_commit_prepared_txn;
cb->rollback_prepared_cb = pgoutput_rollback_prepared_txn;
cb->filter_by_origin_cb = pgoutput_origin_filter;
cb->shutdown_cb = pgoutput_shutdown;
/* transaction streaming */
cb->stream_start_cb = pgoutput_stream_start;
cb->stream_stop_cb = pgoutput_stream_stop;
cb->stream_abort_cb = pgoutput_stream_abort;
cb->stream_commit_cb = pgoutput_stream_commit;
cb->stream_change_cb = pgoutput_change;
cb->stream_message_cb = pgoutput_message;
cb->stream_truncate_cb = pgoutput_truncate;
/* transaction streaming - two-phase commit */
cb->stream_prepare_cb = pgoutput_stream_prepare_txn;
}
6 个 callback 对应 6 类协议消息:
| Callback | 协议消息 | 含义 |
|---|---|---|
stream_start_cb |
STREAM_START ('S') |
开始流式一个事务(可能分多段) |
stream_change_cb |
STREAM_CHANGE (在 chunk 内) |
流式一条 INSERT/UPDATE/DELETE |
stream_stop_cb |
STREAM_STOP ('E') |
当前 chunk 结束(事务可能继续) |
stream_commit_cb |
STREAM_COMMIT ('c') |
事务提交,stream 结束 |
stream_abort_cb |
STREAM_ABORT ('A') |
事务回滚,丢弃所有变更 |
stream_prepare_cb |
STREAM_PREPARE ('p') |
两阶段提交 prepare |
1.4 协议消息类型枚举
源码位置:src/include/replication/logicalproto.h:57。
typedef enum LogicalRepMsgType
{
LOGICAL_REP_MSG_BEGIN = 'B',
LOGICAL_REP_MSG_COMMIT = 'C',
LOGICAL_REP_MSG_ORIGIN = 'O',
LOGICAL_REP_MSG_INSERT = 'I',
LOGICAL_REP_MSG_UPDATE = 'U',
LOGICAL_REP_MSG_DELETE = 'D',
LOGICAL_REP_MSG_TRUNCATE = 'T',
LOGICAL_REP_MSG_RELATION = 'R',
LOGICAL_REP_MSG_TYPE = 'Y',
LOGICAL_REP_MSG_MESSAGE = 'M',
LOGICAL_REP_MSG_BEGIN_PREPARE = 'b',
LOGICAL_REP_MSG_PREPARE = 'P',
LOGICAL_REP_MSG_COMMIT_PREPARED = 'K',
LOGICAL_REP_MSG_ROLLBACK_PREPARED = 'r',
LOGICAL_REP_MSG_STREAM_START = 'S', // ← 本文重点
LOGICAL_REP_MSG_STREAM_STOP = 'E', // ← 本文重点
LOGICAL_REP_MSG_STREAM_COMMIT = 'c', // ← 本文重点
LOGICAL_REP_MSG_STREAM_ABORT = 'A', // ← 本文重点
LOGICAL_REP_MSG_STREAM_PREPARE = 'p', // ← 本文重点
} LogicalRepMsgType;
二、一个事务的完整生命周期(分阶段)
配置: logical_decoding_work_mem=64kB + streaming='parallel',意味着几乎每个变更都可能触发一次 stream 循环。
2.1 阶段 1:WAL 变更进入 Reorder Buffer
源码位置:src/backend/replication/logical/reorderbuffer.c::ReorderBufferQueueChange()(L860 附近)。
// src/backend/replication/logical/reorderbuffer.c:811-867
ReorderBufferQueueChange(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
ReorderBufferChange *change, bool toast_insert)
{
ReorderBufferTXN *txn;
txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
/*
* If we have detected that the transaction is aborted while streaming the
* previous changes or by checking its CLOG, there is no point in
* collecting further changes for it.
*/
if (rbtxn_is_aborted(txn))
{
/*
* We don't need to update memory accounting for this change as we
* have not added it to the queue yet.
*/
ReorderBufferFreeChange(rb, change, false);
return;
}
/*
* The changes that are sent downstream are considered streamable. We
* remember such transactions so that only those will later be considered
* for streaming.
*/
if (change->action == REORDER_BUFFER_CHANGE_INSERT ||
change->action == REORDER_BUFFER_CHANGE_UPDATE ||
change->action == REORDER_BUFFER_CHANGE_DELETE ||
change->action == REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT ||
change->action == REORDER_BUFFER_CHANGE_TRUNCATE ||
change->action == REORDER_BUFFER_CHANGE_MESSAGE)
{
ReorderBufferTXN *toptxn = rbtxn_get_toptxn(txn);
toptxn->txn_flags |= RBTXN_HAS_STREAMABLE_CHANGE;
}
change->lsn = lsn;
change->txn = txn;
Assert(InvalidXLogRecPtr != lsn);
dlist_push_tail(&txn->changes, &change->node);
txn->nentries++;
txn->nentries_mem++;
/* update memory accounting information */
ReorderBufferChangeMemoryUpdate(rb, change, NULL, true,
ReorderBufferChangeSize(change));
/* process partial change */
ReorderBufferProcessPartialChange(rb, txn, change, toast_insert);
/* check the memory limits and evict something if needed */
ReorderBufferCheckMemoryLimit(rb);
}
2.2 阶段 2:触发 stream 的检查函数
源码位置:src/backend/replication/logical/reorderbuffer.c:3883。
// src/backend/replication/logical/reorderbuffer.c:4025-4099
ReorderBufferCheckMemoryLimit(ReorderBuffer *rb)
{
ReorderBufferTXN *txn;
/*
* Bail out if debug_logical_replication_streaming is buffered and we
* haven't exceeded the memory limit.
*/
if (debug_logical_replication_streaming == DEBUG_LOGICAL_REP_STREAMING_BUFFERED &&
rb->size < logical_decoding_work_mem * (Size) 1024)
return;
/*
* If debug_logical_replication_streaming is immediate, loop until there's
* no change. Otherwise, loop until we reach under the memory limit. One
* might think that just by evicting the largest (sub)transaction we will
* come under the memory limit based on assumption that the selected
* transaction is at least as large as the most recent change (which
* caused us to go over the memory limit). However, that is not true
* because a user can reduce the logical_decoding_work_mem to a smaller
* value before the most recent change.
*/
while (rb->size >= logical_decoding_work_mem * (Size) 1024 ||
(debug_logical_replication_streaming == DEBUG_LOGICAL_REP_STREAMING_IMMEDIATE &&
rb->size > 0))
{
/*
* Pick the largest non-aborted transaction and evict it from memory
* by streaming, if possible. Otherwise, spill to disk.
*/
if (ReorderBufferCanStartStreaming(rb) &&
(txn = ReorderBufferLargestStreamableTopTXN(rb)) != NULL)
{
/* we know there has to be one, because the size is not zero */
Assert(txn && rbtxn_is_toptxn(txn));
Assert(txn->total_size > 0);
Assert(rb->size >= txn->total_size);
/* skip the transaction if aborted */
if (ReorderBufferCheckAndTruncateAbortedTXN(rb, txn))
continue;
ReorderBufferStreamTXN(rb, txn);
}
else
{
/*
* Pick the largest transaction (or subtransaction) and evict it
* from memory by serializing it to disk.
*/
txn = ReorderBufferLargestTXN(rb);
/* we know there has to be one, because the size is not zero */
Assert(txn);
Assert(txn->size > 0);
Assert(rb->size >= txn->size);
/* skip the transaction if aborted */
if (ReorderBufferCheckAndTruncateAbortedTXN(rb, txn))
continue;
ReorderBufferSerializeTXN(rb, txn);
}
/*
* After eviction, the transaction should have no entries in memory,
* and should use 0 bytes for changes.
*/
Assert(txn->size == 0);
Assert(txn->nentries_mem == 0);
}
/* We must be under the memory limit now. */
Assert(rb->size < logical_decoding_work_mem * (Size) 1024);
}
关键判断:
| 条件 | 含义 |
|---|---|
debug_logical_replication_streaming == BUFFERED && rb->size < limit |
内存还够,跳过 |
rb->size >= logical_decoding_work_mem * 1024 |
内存用满,进入 while 循环 |
ReorderBufferCanStartStreaming(rb) |
snapshot builder 已到 CONSISTENT |
ReorderBufferLargestStreamableTopTXN(rb) |
找到最大的可 stream 的 top txn |
2.3 阶段 3:挑选”最大可流式”事务
源码位置:src/backend/replication/logical/reorderbuffer.c:3833。
// src/backend/replication/logical/reorderbuffer.c:3975-4009
ReorderBufferLargestStreamableTopTXN(ReorderBuffer *rb)
{
dlist_iter iter;
Size largest_size = 0;
ReorderBufferTXN *largest = NULL;
/* Find the largest top-level transaction having a base snapshot. */
dlist_foreach(iter, &rb->txns_by_base_snapshot_lsn)
{
ReorderBufferTXN *txn;
txn = dlist_container(ReorderBufferTXN, base_snapshot_node, iter.cur);
/* must not be a subtxn */
Assert(!rbtxn_is_known_subxact(txn));
/* base_snapshot must be set */
Assert(txn->base_snapshot != NULL);
/* Don't consider these kinds of transactions for eviction. */
if (rbtxn_has_partial_change(txn) ||
!rbtxn_has_streamable_change(txn) ||
rbtxn_is_aborted(txn))
continue;
/* Find the largest of the eviction candidates. */
if ((largest == NULL || txn->total_size > largest_size) &&
(txn->total_size > 0))
{
largest = txn;
largest_size = txn->total_size;
}
}
return largest;
}
关键过滤:
rbtxn_has_partial_change(txn)—— 有未完成的变更(toast chunks / speculative insert),不能 stream!rbtxn_has_streamable_change(txn)—— 没有任何可 stream 的变更rbtxn_is_aborted(txn)—— 已回滚的事务
挑选策略:遍历 txns_by_base_snapshot_lsn 链表(按 base_snapshot LSN 排序),选 total_size 最大的。
2.4 阶段 4:实际流式事务
源码位置:src/backend/replication/logical/reorderbuffer.c:4308。
// src/backend/replication/logical/reorderbuffer.c:4450-4561
ReorderBufferStreamTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
{
Snapshot snapshot_now;
CommandId command_id;
Size stream_bytes;
bool txn_is_streamed;
/* We can never reach here for a subtransaction. */
Assert(rbtxn_is_toptxn(txn));
/*
* We can't make any assumptions about base snapshot here, similar to what
* ReorderBufferCommit() does. That relies on base_snapshot getting
* transferred from subxact in ReorderBufferCommitChild(), but that was
* not yet called as the transaction is in-progress.
*
* So just walk the subxacts and use the same logic here. But we only need
* to do that once, when the transaction is streamed for the first time.
* After that we need to reuse the snapshot from the previous run.
*
* Unlike DecodeCommit which adds xids of all the subtransactions in
* snapshot's xip array via SnapBuildCommitTxn, we can't do that here but
* we do add them to subxip array instead via ReorderBufferCopySnap. This
* allows the catalog changes made in subtransactions decoded till now to
* be visible.
*/
if (txn->snapshot_now == NULL)
{
dlist_iter subxact_i;
/* make sure this transaction is streamed for the first time */
Assert(!rbtxn_is_streamed(txn));
/* at the beginning we should have invalid command ID */
Assert(txn->command_id == InvalidCommandId);
dlist_foreach(subxact_i, &txn->subtxns)
{
ReorderBufferTXN *subtxn;
subtxn = dlist_container(ReorderBufferTXN, node, subxact_i.cur);
ReorderBufferTransferSnapToParent(txn, subtxn);
}
/*
* If this transaction has no snapshot, it didn't make any changes to
* the database till now, so there's nothing to decode.
*/
if (txn->base_snapshot == NULL)
{
Assert(txn->ninvalidations == 0);
return;
}
command_id = FirstCommandId;
snapshot_now = ReorderBufferCopySnap(rb, txn->base_snapshot,
txn, command_id);
}
else
{
/* the transaction must have been already streamed */
Assert(rbtxn_is_streamed(txn));
/*
* Nah, we already have snapshot from the previous streaming run. We
* assume new subxacts can't move the LSN backwards, and so can't beat
* the LSN condition in the previous branch (so no need to walk
* through subxacts again). In fact, we must not do that as we may be
* using snapshot half-way through the subxact.
*/
command_id = txn->command_id;
/*
* We can't use txn->snapshot_now directly because after the last
* streaming run, we might have got some new sub-transactions. So we
* need to add them to the snapshot.
*/
snapshot_now = ReorderBufferCopySnap(rb, txn->snapshot_now,
txn, command_id);
/* Free the previously copied snapshot. */
Assert(txn->snapshot_now->copied);
ReorderBufferFreeSnap(rb, txn->snapshot_now);
txn->snapshot_now = NULL;
}
/*
* Remember this information to be used later to update stats. We can't
* update the stats here as an error while processing the changes would
* lead to the accumulation of stats even though we haven't streamed all
* the changes.
*/
txn_is_streamed = rbtxn_is_streamed(txn);
stream_bytes = txn->total_size;
/* Process and send the changes to output plugin. */
ReorderBufferProcessTXN(rb, txn, InvalidXLogRecPtr, snapshot_now,
command_id, true);
rb->streamCount += 1;
rb->streamBytes += stream_bytes;
/* Don't consider already streamed transaction. */
rb->streamTxns += (txn_is_streamed) ? 0 : 1;
/* update the decoding stats */
UpdateDecodingStats((LogicalDecodingContext *) rb->private_data);
Assert(dlist_is_empty(&txn->changes));
Assert(txn->nentries == 0);
Assert(txn->nentries_mem == 0);
}
2.5 阶段 5:ReorderBufferProcessTXN 内部
源码位置:src/backend/replication/logical/reorderbuffer.c:2198。
这是 发送协议消息的核心循环:
关键代码片段(精简):
// src/backend/replication/logical/reorderbuffer.c:2214-2813
ReorderBufferProcessTXN(ReorderBuffer *rb, ReorderBufferTXN *txn,
XLogRecPtr commit_lsn,
volatile Snapshot snapshot_now,
volatile CommandId command_id,
bool streaming)
{
bool using_subtxn;
MemoryContext ccxt = CurrentMemoryContext;
ReorderBufferIterTXNState *volatile iterstate = NULL;
volatile XLogRecPtr prev_lsn = InvalidXLogRecPtr;
ReorderBufferChange *volatile specinsert = NULL;
volatile bool stream_started = false;
ReorderBufferTXN *volatile curtxn = NULL;
/* build data to be able to lookup the CommandIds of catalog tuples */
ReorderBufferBuildTupleCidHash(rb, txn);
/* setup the initial snapshot */
SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
/*
* Decoding needs access to syscaches et al., which in turn use
* heavyweight locks and such. Thus we need to have enough state around to
* keep track of those. The easiest way is to simply use a transaction
* internally. That also allows us to easily enforce that nothing writes
* to the database by checking for xid assignments.
*
* When we're called via the SQL SRF there's already a transaction
* started, so start an explicit subtransaction there.
*/
using_subtxn = IsTransactionOrTransactionBlock();
PG_TRY();
{
ReorderBufferChange *change;
int changes_count = 0; /* used to accumulate the number of
* changes */
if (using_subtxn)
BeginInternalSubTransaction(streaming ? "stream" : "replay");
else
StartTransactionCommand();
/*
* We only need to send begin/begin-prepare for non-streamed
* transactions.
*/
if (!streaming)
{
if (rbtxn_is_prepared(txn))
rb->begin_prepare(rb, txn);
else
rb->begin(rb, txn);
}
ReorderBufferIterTXNInit(rb, txn, &iterstate);
while ((change = ReorderBufferIterTXNNext(rb, iterstate)) != NULL)
{
Relation relation = NULL;
Oid reloid;
CHECK_FOR_INTERRUPTS();
/*
* We can't call start stream callback before processing first
* change.
*/
if (prev_lsn == InvalidXLogRecPtr)
{
if (streaming)
{
txn->origin_id = change->origin_id;
rb->stream_start(rb, txn, change->lsn);
stream_started = true;
}
}
/*
* Enforce correct ordering of changes, merged from multiple
* subtransactions. The changes may have the same LSN due to
* MULTI_INSERT xlog records.
*/
Assert(prev_lsn == InvalidXLogRecPtr || prev_lsn <= change->lsn);
prev_lsn = change->lsn;
/*
* Set the current xid to detect concurrent aborts. This is
* required for the cases when we decode the changes before the
* COMMIT record is processed.
*/
if (streaming || rbtxn_is_prepared(change->txn))
{
curtxn = change->txn;
SetupCheckXidLive(curtxn->xid);
}
switch (change->action)
{
case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
/*
* Confirmation for speculative insertion arrived. Simply
* use as a normal record. It'll be cleaned up at the end
* of INSERT processing.
*/
if (specinsert == NULL)
elog(ERROR, "invalid ordering of speculative insertion changes");
Assert(specinsert->data.tp.oldtuple == NULL);
change = specinsert;
change->action = REORDER_BUFFER_CHANGE_INSERT;
/* intentionally fall through */
case REORDER_BUFFER_CHANGE_INSERT:
case REORDER_BUFFER_CHANGE_UPDATE:
case REORDER_BUFFER_CHANGE_DELETE:
Assert(snapshot_now);
reloid = RelidByRelfilenumber(change->data.tp.rlocator.spcOid,
change->data.tp.rlocator.relNumber);
/*
* Mapped catalog tuple without data, emitted while
* catalog table was in the process of being rewritten. We
* can fail to look up the relfilenumber, because the
* relmapper has no "historic" view, in contrast to the
* normal catalog during decoding. Thus repeated rewrites
* can cause a lookup failure. That's OK because we do not
* decode catalog changes anyway. Normally such tuples
* would be skipped over below, but we can't identify
* whether the table should be logically logged without
* mapping the relfilenumber to the oid.
*/
if (reloid == InvalidOid &&
change->data.tp.newtuple == NULL &&
change->data.tp.oldtuple == NULL)
goto change_done;
else if (reloid == InvalidOid)
elog(ERROR, "could not map filenumber \"%s\" to relation OID",
relpathperm(change->data.tp.rlocator,
MAIN_FORKNUM).str);
relation = RelationIdGetRelation(reloid);
if (!RelationIsValid(relation))
elog(ERROR, "could not open relation with OID %u (for filenumber \"%s\")",
reloid,
relpathperm(change->data.tp.rlocator,
MAIN_FORKNUM).str);
if (!RelationIsLogicallyLogged(relation))
goto change_done;
/*
* Ignore temporary heaps created during DDL unless the
* plugin has asked for them.
*/
if (relation->rd_rel->relrewrite && !rb->output_rewrites)
goto change_done;
/*
* For now ignore sequence changes entirely. Most of the
* time they don't log changes using records we
* understand, so it doesn't make sense to handle the few
* cases we do.
*/
if (relation->rd_rel->relkind == RELKIND_SEQUENCE)
goto change_done;
/* user-triggered change */
if (!IsToastRelation(relation))
{
ReorderBufferToastReplace(rb, txn, relation, change);
ReorderBufferApplyChange(rb, txn, relation, change,
streaming);
/*
* Only clear reassembled toast chunks if we're sure
* they're not required anymore. The creator of the
* tuple tells us.
*/
if (change->data.tp.clear_toast_afterwards)
ReorderBufferToastReset(rb, txn);
}
/* we're not interested in toast deletions */
else if (change->action == REORDER_BUFFER_CHANGE_INSERT)
{
/*
* Need to reassemble the full toasted Datum in
* memory, to ensure the chunks don't get reused till
* we're done remove it from the list of this
* transaction's changes. Otherwise it will get
* freed/reused while restoring spooled data from
* disk.
*/
Assert(change->data.tp.newtuple != NULL);
dlist_delete(&change->node);
ReorderBufferToastAppendChunk(rb, txn, relation,
change);
}
change_done:
/*
* If speculative insertion was confirmed, the record
* isn't needed anymore.
*/
if (specinsert != NULL)
{
ReorderBufferFreeChange(rb, specinsert, true);
specinsert = NULL;
}
if (RelationIsValid(relation))
{
RelationClose(relation);
relation = NULL;
}
break;
case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
/*
* Speculative insertions are dealt with by delaying the
* processing of the insert until the confirmation record
* arrives. For that we simply unlink the record from the
* chain, so it does not get freed/reused while restoring
* spooled data from disk.
*
* This is safe in the face of concurrent catalog changes
* because the relevant relation can't be changed between
* speculative insertion and confirmation due to
* CheckTableNotInUse() and locking.
*/
/* clear out a pending (= failed) speculative insertion */
if (specinsert != NULL)
{
ReorderBufferFreeChange(rb, specinsert, true);
specinsert = NULL;
}
/* and memorize the pending insertion */
dlist_delete(&change->node);
specinsert = change;
break;
case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT:
/*
* Abort for speculative insertion arrived. So cleanup the
* specinsert tuple and toast hash.
*
* Note that we get the spec abort change for each toast
* entry but we need to perform the cleanup only the first
* time we get it for the main table.
*/
if (specinsert != NULL)
{
/*
* We must clean the toast hash before processing a
* completely new tuple to avoid confusion about the
* previous tuple's toast chunks.
*/
Assert(change->data.tp.clear_toast_afterwards);
ReorderBufferToastReset(rb, txn);
/* We don't need this record anymore. */
ReorderBufferFreeChange(rb, specinsert, true);
specinsert = NULL;
}
break;
case REORDER_BUFFER_CHANGE_TRUNCATE:
{
int i;
int nrelids = change->data.truncate.nrelids;
int nrelations = 0;
Relation *relations;
relations = palloc0(nrelids * sizeof(Relation));
for (i = 0; i < nrelids; i++)
{
Oid relid = change->data.truncate.relids[i];
Relation rel;
rel = RelationIdGetRelation(relid);
if (!RelationIsValid(rel))
elog(ERROR, "could not open relation with OID %u", relid);
if (!RelationIsLogicallyLogged(rel))
{
RelationClose(rel);
continue;
}
relations[nrelations++] = rel;
}
/* Apply the truncate. */
ReorderBufferApplyTruncate(rb, txn, nrelations,
relations, change,
streaming);
for (i = 0; i < nrelations; i++)
RelationClose(relations[i]);
break;
}
case REORDER_BUFFER_CHANGE_MESSAGE:
ReorderBufferApplyMessage(rb, txn, change, streaming);
break;
case REORDER_BUFFER_CHANGE_INVALIDATION:
/* Execute the invalidation messages locally */
ReorderBufferExecuteInvalidations(change->data.inval.ninvalidations,
change->data.inval.invalidations);
break;
case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
/* get rid of the old */
TeardownHistoricSnapshot(false);
if (snapshot_now->copied)
{
ReorderBufferFreeSnap(rb, snapshot_now);
snapshot_now =
ReorderBufferCopySnap(rb, change->data.snapshot,
txn, command_id);
}
/*
* Restored from disk, need to be careful not to double
* free. We could introduce refcounting for that, but for
* now this seems infrequent enough not to care.
*/
else if (change->data.snapshot->copied)
{
snapshot_now =
ReorderBufferCopySnap(rb, change->data.snapshot,
txn, command_id);
}
else
{
snapshot_now = change->data.snapshot;
}
/* and continue with the new one */
SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
break;
case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
Assert(change->data.command_id != InvalidCommandId);
if (command_id < change->data.command_id)
{
command_id = change->data.command_id;
if (!snapshot_now->copied)
{
/* we don't use the global one anymore */
snapshot_now = ReorderBufferCopySnap(rb, snapshot_now,
txn, command_id);
}
snapshot_now->curcid = command_id;
TeardownHistoricSnapshot(false);
SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
}
break;
case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
elog(ERROR, "tuplecid value in changequeue");
break;
}
/*
* It is possible that the data is not sent to downstream for a
* long time either because the output plugin filtered it or there
* is a DDL that generates a lot of data that is not processed by
* the plugin. So, in such cases, the downstream can timeout. To
* avoid that we try to send a keepalive message if required.
* Trying to send a keepalive message after every change has some
* overhead, but testing showed there is no noticeable overhead if
* we do it after every ~100 changes.
*/
#define CHANGES_THRESHOLD 100
if (++changes_count >= CHANGES_THRESHOLD)
{
rb->update_progress_txn(rb, txn, prev_lsn);
changes_count = 0;
}
}
/* speculative insertion record must be freed by now */
Assert(!specinsert);
/* clean up the iterator */
ReorderBufferIterTXNFinish(rb, iterstate);
iterstate = NULL;
/*
* Update total transaction count and total bytes processed by the
* transaction and its subtransactions. Ensure to not count the
* streamed transaction multiple times.
*
* Note that the statistics computation has to be done after
* ReorderBufferIterTXNFinish as it releases the serialized change
* which we have already accounted in ReorderBufferIterTXNNext.
*/
if (!rbtxn_is_streamed(txn))
rb->totalTxns++;
rb->totalBytes += txn->total_size;
/*
* Done with current changes, send the last message for this set of
* changes depending upon streaming mode.
*/
if (streaming)
{
if (stream_started)
{
rb->stream_stop(rb, txn, prev_lsn);
stream_started = false;
}
}
else
{
/*
* Call either PREPARE (for two-phase transactions) or COMMIT (for
* regular ones).
*/
if (rbtxn_is_prepared(txn))
{
Assert(!rbtxn_sent_prepare(txn));
rb->prepare(rb, txn, commit_lsn);
txn->txn_flags |= RBTXN_SENT_PREPARE;
}
else
rb->commit(rb, txn, commit_lsn);
}
/* this is just a sanity check against bad output plugin behaviour */
if (GetCurrentTransactionIdIfAny() != InvalidTransactionId)
elog(ERROR, "output plugin used XID %u",
GetCurrentTransactionId());
/*
* Remember the command ID and snapshot for the next set of changes in
* streaming mode.
*/
if (streaming)
ReorderBufferSaveTXNSnapshot(rb, txn, snapshot_now, command_id);
else if (snapshot_now->copied)
ReorderBufferFreeSnap(rb, snapshot_now);
/* cleanup */
TeardownHistoricSnapshot(false);
/*
* Aborting the current (sub-)transaction as a whole has the right
* semantics. We want all locks acquired in here to be released, not
* reassigned to the parent and we do not want any database access
* have persistent effects.
*/
AbortCurrentTransaction();
/* make sure there's no cache pollution */
if (rbtxn_distr_inval_overflowed(txn))
{
Assert(txn->ninvalidations_distributed == 0);
InvalidateSystemCaches();
}
else
{
ReorderBufferExecuteInvalidations(txn->ninvalidations, txn->invalidations);
ReorderBufferExecuteInvalidations(txn->ninvalidations_distributed,
txn->invalidations_distributed);
}
if (using_subtxn)
RollbackAndReleaseCurrentSubTransaction();
/*
* We are here due to one of the four reasons: 1. Decoding an
* in-progress txn. 2. Decoding a prepared txn. 3. Decoding of a
* prepared txn that was (partially) streamed. 4. Decoding a committed
* txn.
*
* For 1, we allow truncation of txn data by removing the changes
* already streamed but still keeping other things like invalidations,
* snapshot, and tuplecids. For 2 and 3, we indicate
* ReorderBufferTruncateTXN to do more elaborate truncation of txn
* data as the entire transaction has been decoded except for commit.
* For 4, as the entire txn has been decoded, we can fully clean up
* the TXN reorder buffer.
*/
if (streaming || rbtxn_is_prepared(txn))
{
if (streaming)
ReorderBufferMaybeMarkTXNStreamed(rb, txn);
ReorderBufferTruncateTXN(rb, txn, rbtxn_is_prepared(txn));
/* Reset the CheckXidAlive */
CheckXidAlive = InvalidTransactionId;
}
else
ReorderBufferCleanupTXN(rb, txn);
}
PG_CATCH();
{
MemoryContext ecxt = MemoryContextSwitchTo(ccxt);
ErrorData *errdata = CopyErrorData();
/* TODO: Encapsulate cleanup from the PG_TRY and PG_CATCH blocks */
if (iterstate)
ReorderBufferIterTXNFinish(rb, iterstate);
TeardownHistoricSnapshot(true);
/*
* Force cache invalidation to happen outside of a valid transaction
* to prevent catalog access as we just caught an error.
*/
AbortCurrentTransaction();
/* make sure there's no cache pollution */
if (rbtxn_distr_inval_overflowed(txn))
{
Assert(txn->ninvalidations_distributed == 0);
InvalidateSystemCaches();
}
else
{
ReorderBufferExecuteInvalidations(txn->ninvalidations, txn->invalidations);
ReorderBufferExecuteInvalidations(txn->ninvalidations_distributed,
txn->invalidations_distributed);
}
if (using_subtxn)
RollbackAndReleaseCurrentSubTransaction();
/* Free the specinsert change before freeing the ReorderBufferTXN */
if (specinsert != NULL)
{
ReorderBufferFreeChange(rb, specinsert, true);
specinsert = NULL;
}
/*
* The error code ERRCODE_TRANSACTION_ROLLBACK indicates a concurrent
* abort of the (sub)transaction we are streaming or preparing. We
* need to do the cleanup and return gracefully on this error, see
* SetupCheckXidLive.
*
* This error code can be thrown by one of the callbacks we call
* during decoding so we need to ensure that we return gracefully only
* when we are sending the data in streaming mode and the streaming is
* not finished yet or when we are sending the data out on a PREPARE
* during a two-phase commit.
*/
if (errdata->sqlerrcode == ERRCODE_TRANSACTION_ROLLBACK &&
(stream_started || rbtxn_is_prepared(txn)))
{
/* curtxn must be set for streaming or prepared transactions */
Assert(curtxn);
/* Cleanup the temporary error state. */
FlushErrorState();
FreeErrorData(errdata);
errdata = NULL;
/* Remember the transaction is aborted. */
Assert(!rbtxn_is_committed(curtxn));
curtxn->txn_flags |= RBTXN_IS_ABORTED;
/* Mark the transaction is streamed if appropriate */
if (stream_started)
ReorderBufferMaybeMarkTXNStreamed(rb, txn);
/* Reset the TXN so that it is allowed to stream remaining data. */
ReorderBufferResetTXN(rb, txn, snapshot_now,
command_id, prev_lsn);
}
else
{
ReorderBufferCleanupTXN(rb, txn);
MemoryContextSwitchTo(ecxt);
PG_RE_THROW();
}
}
PG_END_TRY();
}
2.6 阶段 6:最终 COMMIT 路径
源码位置:src/backend/replication/logical/reorderbuffer.c:2813、ReorderBufferCommit 在 L2874。
// src/backend/replication/logical/reorderbuffer.c:2826-2879
ReorderBufferReplay(ReorderBufferTXN *txn,
ReorderBuffer *rb, TransactionId xid,
XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
TimestampTz commit_time,
RepOriginId origin_id, XLogRecPtr origin_lsn)
{
Snapshot snapshot_now;
CommandId command_id = FirstCommandId;
txn->final_lsn = commit_lsn;
txn->end_lsn = end_lsn;
txn->xact_time.commit_time = commit_time;
txn->origin_id = origin_id;
txn->origin_lsn = origin_lsn;
/*
* If the transaction was (partially) streamed, we need to commit it in a
* 'streamed' way. That is, we first stream the remaining part of the
* transaction, and then invoke stream_commit message.
*
* Called after everything (origin ID, LSN, ...) is stored in the
* transaction to avoid passing that information directly.
*/
if (rbtxn_is_streamed(txn))
{
ReorderBufferStreamCommit(rb, txn);
return;
}
/*
* If this transaction has no snapshot, it didn't make any changes to the
* database, so there's nothing to decode. Note that
* ReorderBufferCommitChild will have transferred any snapshots from
* subtransactions if there were any.
*/
if (txn->base_snapshot == NULL)
{
Assert(txn->ninvalidations == 0);
/*
* Removing this txn before a commit might result in the computation
* of an incorrect restart_lsn. See SnapBuildProcessRunningXacts.
*/
if (!rbtxn_is_prepared(txn))
ReorderBufferCleanupTXN(rb, txn);
return;
}
snapshot_now = txn->base_snapshot;
/* Process and send the changes to output plugin. */
ReorderBufferProcessTXN(rb, txn, commit_lsn, snapshot_now,
command_id, false);
}
源码位置:ReorderBufferStreamCommit(L1980):
// src/backend/replication/logical/reorderbuffer.c:1984-2015
ReorderBufferStreamCommit(ReorderBuffer *rb, ReorderBufferTXN *txn)
{
/* we should only call this for previously streamed transactions */
Assert(rbtxn_is_streamed(txn));
ReorderBufferStreamTXN(rb, txn);
if (rbtxn_is_prepared(txn))
{
/*
* Note, we send stream prepare even if a concurrent abort is
* detected. See DecodePrepare for more information.
*/
Assert(!rbtxn_sent_prepare(txn));
rb->stream_prepare(rb, txn, txn->final_lsn);
txn->txn_flags |= RBTXN_SENT_PREPARE;
/*
* This is a PREPARED transaction, part of a two-phase commit. The
* full cleanup will happen as part of the COMMIT PREPAREDs, so now
* just truncate txn by removing changes and tuplecids.
*/
ReorderBufferTruncateTXN(rb, txn, true);
/* Reset the CheckXidAlive */
CheckXidAlive = InvalidTransactionId;
}
else
{
rb->stream_commit(rb, txn, txn->final_lsn);
ReorderBufferCleanupTXN(rb, txn);
}
}
三、pgoutput 输出插件的 6 个 callback
源码位置:src/backend/replication/pgoutput/pgoutput.c。
3.1 pgoutput_stream_start —— 发 STREAM_START
源码位置:src/backend/replication/pgoutput/pgoutput.c:1838。
// src/backend/replication/pgoutput/pgoutput.c:1838-1864
pgoutput_stream_start(struct LogicalDecodingContext *ctx,
ReorderBufferTXN *txn)
{
PGOutputData *data = (PGOutputData *) ctx->output_plugin_private;
bool send_replication_origin = txn->origin_id != InvalidRepOriginId;
/* we can't nest streaming of transactions */
Assert(!data->in_streaming);
/*
* If we already sent the first stream for this transaction then don't
* send the origin id in the subsequent streams.
*/
if (rbtxn_is_streamed(txn))
send_replication_origin = false;
OutputPluginPrepareWrite(ctx, !send_replication_origin);
logicalrep_write_stream_start(ctx->out, txn->xid, !rbtxn_is_streamed(txn));
send_repl_origin(ctx, txn->origin_id, InvalidXLogRecPtr,
send_replication_origin);
OutputPluginWrite(ctx, true);
/* we're streaming a chunk of transaction now */
data->in_streaming = true;
}
协议层(src/backend/replication/logical/proto.c:1061):
// src/backend/replication/logical/proto.c:1061-1073
logicalrep_write_stream_start(StringInfo out,
TransactionId xid, bool first_segment)
{
pq_sendbyte(out, LOGICAL_REP_MSG_STREAM_START);
Assert(TransactionIdIsValid(xid));
/* transaction ID (we're starting to stream, so must be valid) */
pq_sendint32(out, xid);
/* 1 if this is the first streaming segment for this xid */
pq_sendbyte(out, first_segment ? 1 : 0);
}
协议格式(wire protocol):
+---------+---------+---------+---------+---------+
| 'S'(1B) | xid(4B) | first_seg(1B) |
+---------+----------------------+----------------+
3.2 pgoutput_stream_change —— 发 INSERT/UPDATE/DELETE
源码位置:src/backend/replication/pgoutput/pgoutput.c(具体函数实现)。
// 简化版
static void
pgoutput_stream_change(struct LogicalDecodingContext *ctx,
ReorderBufferTXN *txn, Relation relation,
ReorderBufferChange *change)
{
PGOutputData *data = (PGOutputData *) ctx->output_plugin_private;
MemoryContext old;
Assert(data->in_streaming);
/* 先确保订阅端认识这个 relation */
output_relation_info(ctx, relation, ...);
switch (change->action)
{
case REORDER_BUFFER_CHANGE_INSERT:
// 写 LOGICAL_REP_MSG_INSERT + tuple data
OutputPluginPrepareWrite(ctx, true);
logicalrep_write_insert(ctx->out, ...);
OutputPluginWrite(ctx, true);
break;
case REORDER_BUFFER_CHANGE_UPDATE:
// 写 LOGICAL_REP_MSG_UPDATE + new tuple
...
break;
case REORDER_BUFFER_CHANGE_DELETE:
// 写 LOGICAL_REP_MSG_DELETE
...
break;
...
}
}
关键点:
- 每个变更都是一个独立的子消息,嵌在 STREAM_START 和 STREAM_STOP 之间
- 如果是新的 relation,先发 RELATION 消息(描述 schema)
OutputPluginPrepareWrite+logicalrep_write_*+OutputPluginWrite是标准三步
3.3 pgoutput_stream_stop —— 发 STREAM_STOP
源码位置:src/backend/replication/pgoutput/pgoutput.c:1875。
// src/backend/replication/pgoutput/pgoutput.c:1870-1884
pgoutput_stream_stop(struct LogicalDecodingContext *ctx,
ReorderBufferTXN *txn)
{
PGOutputData *data = (PGOutputData *) ctx->output_plugin_private;
/* we should be streaming a transaction */
Assert(data->in_streaming);
OutputPluginPrepareWrite(ctx, true);
logicalrep_write_stream_stop(ctx->out);
OutputPluginWrite(ctx, true);
/* we've stopped streaming a transaction */
data->in_streaming = false;
}
协议格式:
+---------+
| 'E'(1B) |
+---------+
最简单,只是告诉订阅端”当前 chunk 结束,事务可能继续”。
3.4 pgoutput_stream_commit —— 发 STREAM_COMMIT
源码位置:src/backend/replication/pgoutput/pgoutput.c:1924。
// src/backend/replication/pgoutput/pgoutput.c:1924-1944
pgoutput_stream_commit(struct LogicalDecodingContext *ctx,
ReorderBufferTXN *txn,
XLogRecPtr commit_lsn)
{
PGOutputData *data PG_USED_FOR_ASSERTS_ONLY = (PGOutputData *) ctx->output_plugin_private;
/*
* The commit should happen outside streaming block, even for streamed
* transactions. The transaction has to be marked as streamed, though.
*/
Assert(!data->in_streaming);
Assert(rbtxn_is_streamed(txn));
OutputPluginUpdateProgress(ctx, false);
OutputPluginPrepareWrite(ctx, true);
logicalrep_write_stream_commit(ctx->out, txn, commit_lsn);
OutputPluginWrite(ctx, true);
cleanup_rel_sync_cache(txn->xid, true);
}
协议层:
// src/backend/replication/logical/proto.c:1104-1123
logicalrep_write_stream_commit(StringInfo out, ReorderBufferTXN *txn,
XLogRecPtr commit_lsn)
{
uint8 flags = 0;
pq_sendbyte(out, LOGICAL_REP_MSG_STREAM_COMMIT);
Assert(TransactionIdIsValid(txn->xid));
/* transaction ID */
pq_sendint32(out, txn->xid);
/* send the flags field (unused for now) */
pq_sendbyte(out, flags);
/* send fields */
pq_sendint64(out, commit_lsn);
pq_sendint64(out, txn->end_lsn);
pq_sendint64(out, txn->xact_time.commit_time);
}
协议格式:
+---------+----------+---------+-------------+-----------+-----------+-----------+
| 'c'(1B) | xid(4B) | flags(1B)| commit_lsn | end_lsn | committime |
| | | (reserved)| (8B) | (8B) | (8B) |
+---------+----------+---------+-----------+-----------+-----------+
断言 !data->in_streaming 的含义:
STREAM_COMMIT 必须在 streaming 块之外发送。这是协议级别的硬约束,确保订阅端能正确识别”事务结束”。
3.5 pgoutput_stream_abort —— 发 STREAM_ABORT
源码位置:src/backend/replication/pgoutput/pgoutput.c:1891。
// src/backend/replication/pgoutput/pgoutput.c:1891-1917
pgoutput_stream_abort(struct LogicalDecodingContext *ctx,
ReorderBufferTXN *txn,
XLogRecPtr abort_lsn)
{
ReorderBufferTXN *toptxn;
PGOutputData *data = (PGOutputData *) ctx->output_plugin_private;
bool write_abort_info = (data->streaming == LOGICALREP_STREAM_PARALLEL);
/*
* The abort should happen outside streaming block, even for streamed
* transactions. The transaction has to be marked as streamed, though.
*/
Assert(!data->in_streaming);
/* determine the toplevel transaction */
toptxn = rbtxn_get_toptxn(txn);
Assert(rbtxn_is_streamed(toptxn));
OutputPluginPrepareWrite(ctx, true);
logicalrep_write_stream_abort(ctx->out, toptxn->xid, txn->xid, abort_lsn,
txn->xact_time.abort_time, write_abort_info);
OutputPluginWrite(ctx, true);
cleanup_rel_sync_cache(toptxn->xid, false);
}
关键差异:
LOGICALREP_STREAM_PARALLEL模式:写完整 abort 信息(包含 abort_lsn)- 其他模式:只发一个字节的
'A'
源码位置:src/include/catalog/pg_subscription.h:165-177 定义 streaming mode:
#define LOGICALREP_STREAM_OFF 'f'
#define LOGICALREP_STREAM_ON 't'
#define LOGICALREP_STREAM_PARALLEL 'p'
3.6 pgoutput_stream_prepare_txn —— 发 STREAM_PREPARE
源码位置:src/backend/replication/pgoutput/pgoutput.c:1955。
// src/backend/replication/pgoutput/pgoutput.c:1952-1965
pgoutput_stream_prepare_txn(LogicalDecodingContext *ctx,
ReorderBufferTXN *txn,
XLogRecPtr prepare_lsn)
{
Assert(rbtxn_is_streamed(txn));
OutputPluginUpdateProgress(ctx, false);
OutputPluginPrepareWrite(ctx, true);
logicalrep_write_stream_prepare(ctx->out, txn, prepare_lsn);
OutputPluginWrite(ctx, true);
/* Schema cache updates at PREPARE survive ROLLBACK PREPARED. */
cleanup_rel_sync_cache(txn->xid, true);
}
两阶段提交专用,本文不展开。
四、协议层 wrapper 函数
源码位置:src/backend/replication/logical/logical.c:81、stream_start_cb_wrapper 在 L1269。
逻辑层在 RB 和 pgoutput 之间加了一个 wrapper 层,做事务隔离、错误捕获、上下文保护:
// src/backend/replication/logical/logical.c:1364-1410
stream_start_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
XLogRecPtr first_lsn)
{
LogicalDecodingContext *ctx = cache->private_data;
LogicalErrorCallbackState state;
ErrorContextCallback errcallback;
Assert(!ctx->fast_forward);
/* We're only supposed to call this when streaming is supported. */
Assert(ctx->streaming);
/* Push callback + info on the error context stack */
state.ctx = ctx;
state.callback_name = "stream_start";
state.report_location = first_lsn;
errcallback.callback = output_plugin_error_callback;
errcallback.arg = &state;
errcallback.previous = error_context_stack;
error_context_stack = &errcallback;
/* set output state */
ctx->accept_writes = true;
ctx->write_xid = txn->xid;
/*
* Report this message's lsn so replies from clients can give an
* up-to-date answer. This won't ever be enough (and shouldn't be!) to
* confirm receipt of this transaction, but it might allow another
* transaction's commit to be confirmed with one message.
*/
ctx->write_location = first_lsn;
ctx->end_xact = false;
/* in streaming mode, stream_start_cb is required */
if (ctx->callbacks.stream_start_cb == NULL)
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("logical streaming requires a %s callback",
"stream_start_cb")));
ctx->callbacks.stream_start_cb(ctx, txn);
/* Pop the error context stack */
error_context_stack = errcallback.previous;
}
OutputPluginBegin / OutputPluginEnd 用于事务隔离、错误回调、内存上下文切换。
五、完整时序:一个事务从 BEGIN 到 STREAM_COMMIT
把以上整合,看一个具体例子:
场景:发布端执行
BEGIN;
INSERT INTO t VALUES (1, 'a'); -- 30KB
INSERT INTO t VALUES (2, 'b'); -- 30KB
-- 此时总 60KB,接近 64KB 但未满
INSERT INTO t VALUES (3, 'c'); -- 30KB
-- 此时总 90KB,超过 64KB → 触发 stream
INSERT INTO t VALUES (4, 'd'); -- 30KB
COMMIT;
关键观察:
- 每次触发 stream 都是完整的 start+changes+stop 循环
first_segment=1只在第一次,后续都是 0(避免重复发送 origin)- STREAM_COMMIT 必须单独发,且在 streaming 块外
- 事务可能在 COMMIT 时还有未 stream 的变更(此处没有,但 PG 会兜底)
六、为什么 64KB 会让每个事务都触发?
回到最初的问题:logical_decoding_work_mem='64kB' 为什么”几乎每个事务都 stream”?
计算:
实测:TPC-C 单事务 5- 10KB,64KB 限制意味着大约 6-12 个事务就能触发一次 stream。但场景是”每个事务都会触发”,因为:
- 多个事务并发进入 RB,大小累加更快
- 一个事务如果变更多,也很快超 64KB
- 即使单条 INSERT,也可能超 64KB(大字段)
对比默认值 64MB:
| 配置 | 单事务触发频率 | 网络流量 | 订阅端缓冲 |
|---|---|---|---|
| 64MB | 大事务才会 stream | 少 | 高 |
| 64KB | 小事务也 stream | 多 | 低 |
八、监控与诊断
8.1 发布端视角
查看复制槽状态(包括 stream 计数):
SELECT slot_name,
restart_lsn,
confirmed_flush_lsn,
active,
active_pid,
-- PG 18 提供 stream 相关字段
stream_txns,
stream_bytes,
stream_count
FROM pg_replication_slots;
源码位置:src/include/replication/slot.h 定义 ReplicationSlot 结构,streamCount / streamBytes / streamTxns 三个字段。
8.2 看 pgoutput 是否开启 streaming
源码位置:src/backend/replication/pgoutput/pgoutput.c::pgoutput_startup()。
// 简化:订阅端的 streaming 选项通过 wire 协议传过来
// pgoutput 收到后,设置 ctx->callbacks.stream_*_cb
可用 EXPLAIN 或 debug 日志确认:
# postgresql.conf
wal_level = logical
log_min_messages = debug1
log_statement = all
log_replication_commands = on
8.3 监控 stream chunk 频率
通过 pg_stat_replication:
SELECT pid, application_name, state,
sent_lsn, write_lsn, flush_lsn, replay_lsn,
sync_priority, sync_state,
reply_time
FROM pg_stat_replication;
观察指标:
sent_lsn - flush_lsn大 → 订阅端处理慢replay_lsn不动 → 订阅端 worker 异常
8.4 验证 stream 真的发生了
开启 debug_logical_replication_streaming='immediate':
# postgresql.conf
debug_logical_replication_streaming = immediate
源码位置:src/backend/utils/misc/guc_tables.c:5418、src/backend/replication/logical/reorderbuffer.c:3870。
// src/backend/replication/logical/reorderbuffer.c:4025-4099
ReorderBufferCheckMemoryLimit(ReorderBuffer *rb)
{
ReorderBufferTXN *txn;
/*
* Bail out if debug_logical_replication_streaming is buffered and we
* haven't exceeded the memory limit.
*/
if (debug_logical_replication_streaming == DEBUG_LOGICAL_REP_STREAMING_BUFFERED &&
rb->size < logical_decoding_work_mem * (Size) 1024)
return;
/*
* If debug_logical_replication_streaming is immediate, loop until there's
* no change. Otherwise, loop until we reach under the memory limit. One
* might think that just by evicting the largest (sub)transaction we will
* come under the memory limit based on assumption that the selected
* transaction is at least as large as the most recent change (which
* caused us to go over the memory limit). However, that is not true
* because a user can reduce the logical_decoding_work_mem to a smaller
* value before the most recent change.
*/
while (rb->size >= logical_decoding_work_mem * (Size) 1024 ||
(debug_logical_replication_streaming == DEBUG_LOGICAL_REP_STREAMING_IMMEDIATE &&
rb->size > 0))
{
/*
* Pick the largest non-aborted transaction and evict it from memory
* by streaming, if possible. Otherwise, spill to disk.
*/
if (ReorderBufferCanStartStreaming(rb) &&
(txn = ReorderBufferLargestStreamableTopTXN(rb)) != NULL)
{
/* we know there has to be one, because the size is not zero */
Assert(txn && rbtxn_is_toptxn(txn));
Assert(txn->total_size > 0);
Assert(rb->size >= txn->total_size);
/* skip the transaction if aborted */
if (ReorderBufferCheckAndTruncateAbortedTXN(rb, txn))
continue;
ReorderBufferStreamTXN(rb, txn);
}
else
{
/*
* Pick the largest transaction (or subtransaction) and evict it
* from memory by serializing it to disk.
*/
txn = ReorderBufferLargestTXN(rb);
/* we know there has to be one, because the size is not zero */
Assert(txn);
Assert(txn->size > 0);
Assert(rb->size >= txn->size);
/* skip the transaction if aborted */
if (ReorderBufferCheckAndTruncateAbortedTXN(rb, txn))
continue;
ReorderBufferSerializeTXN(rb, txn);
}
/*
* After eviction, the transaction should have no entries in memory,
* and should use 0 bytes for changes.
*/
Assert(txn->size == 0);
Assert(txn->nentries_mem == 0);
}
/* We must be under the memory limit now. */
Assert(rb->size < logical_decoding_work_mem * (Size) 1024);
}
设为 immediate 时,每条变更后立即触发 stream,可以用来压力测试和验证流式路径。
九、调优建议
9.1 发布端
| 参数 | 推荐值 | 备注 |
|---|---|---|
logical_decoding_work_mem |
64MB(默认)~ 256MB | 不推荐 64KB,除非有特定压测需求 |
debug_logical_replication_streaming |
buffered(默认) |
生产环境不要用 immediate |
wal_level |
logical |
必须 |
max_replication_slots |
≥ 订阅数 + 备用 | |
max_wal_senders |
≥ max_replication_slots |
9.2 何时用 logical_decoding_work_mem=64KB
仅以下场景:
- 压力测试 / 性能调优:验证极端流式场景
- 调试:开启
debug_logical_replication_streaming=immediate配合 - 特殊业务:要求订阅端实时接收(不能容忍订阅端缓冲)
生产环境几乎不用——过小的内存阈值会导致:
- stream 频繁触发,网络包数爆增
pg_replication_slots.streamCount暴涨- 订阅端 leader apply worker 频繁分配 parallel worker
十、源码速查
| 关注点 | 文件 | 行/函数 |
|---|---|---|
LogicalRepMsgType 枚举 |
src/include/replication/logicalproto.h |
L57-79 |
logical_decoding_work_mem GUC |
src/backend/utils/misc/guc_tables.c |
L2604 |
ReorderBufferCheckMemoryLimit |
src/backend/replication/logical/reorderbuffer.c |
L3883 |
ReorderBufferLargestStreamableTopTXN |
src/backend/replication/logical/reorderbuffer.c |
L3833 |
ReorderBufferStreamTXN |
src/backend/replication/logical/reorderbuffer.c |
L4308 |
ReorderBufferStreamCommit |
src/backend/replication/logical/reorderbuffer.c |
L1980 |
ReorderBufferProcessTXN |
src/backend/replication/logical/reorderbuffer.c |
L2198 |
ReorderBufferReplay |
src/backend/replication/logical/reorderbuffer.c |
L2813 |
ReorderBufferCommit |
src/backend/replication/logical/reorderbuffer.c |
L2874 |
ReorderBufferCanStream |
src/backend/replication/logical/reorderbuffer.c |
L4273 |
ReorderBufferCanStartStreaming |
src/backend/replication/logical/reorderbuffer.c |
L4282 |
pgoutput_stream_start |
src/backend/replication/pgoutput/pgoutput.c |
L1838 |
pgoutput_stream_stop |
src/backend/replication/pgoutput/pgoutput.c |
L1875 |
pgoutput_stream_abort |
src/backend/replication/pgoutput/pgoutput.c |
L1891 |
pgoutput_stream_commit |
src/backend/replication/pgoutput/pgoutput.c |
L1924 |
pgoutput_stream_prepare_txn |
src/backend/replication/pgoutput/pgoutput.c |
L1955 |
| callback 注册 | src/backend/replication/pgoutput/pgoutput.c |
L278 |
logicalrep_write_stream_start |
src/backend/replication/logical/proto.c |
L1061 |
logicalrep_write_stream_commit |
src/backend/replication/logical/proto.c |
L1104 |
stream_start_cb_wrapper |
src/backend/replication/logical/logical.c |
L1269 |
ctx->streaming 设置 |
src/backend/replication/logical/logical.c |
L238 |
streaming='parallel' 协商 |
src/backend/replication/logical/worker.c |
L4455-4475 |
rbtxn_is_streamed |
src/include/replication/reorderbuffer.h |
全文 |
十一、参考
- PostgreSQL 18 逻辑复制 streaming 与 spill 文件分析
- PostgreSQL 18 逻辑复制 reorder buffer 与事务机制
- PostgreSQL 18 Apply Parallel Worker 运行机制
- PostgreSQL 官方文档 - Logical Streaming for Large Transactions
- 源码:
~/cwork/postgresql