配套源码:
src/backend/replication/{walsender.c, slot.c, slotfuncs.c}+src/backend/replication/logical/*+src/include/access/xlogdefs.h读完本文你会理解:
- WAL 内部 LSN 的物理布局(段文件 / 页 / 记录)
- 复制槽的 5+ 个 LSN 字段:
restart_lsn、confirmed_flush_lsn、candidate_xmin_lsn、catalog_xmin、two_phase_at- walsender 的 6+ 个 LSN:
sentPtr、write、flush、apply、end_recptr、flushPtr- 订阅端 worker 的 LSN:
commit_lsn、end_lsn、origin_lsn、last_lsn、reply_lsn- 每个 LSN 在何时由谁推进 —— 全链路推进的精确时机
- 一次 UPDATE 事务 经历的 LSN 变化(具体数字举例)
目录
- 一、LSN 基础与全局概念
- 二、全链路 LSN 推进全景图
- 三、WAL 内部的 LSN 物理布局
- 四、复制槽的 LSN 字段详解
- 五、walsender 的 LSN 变量详解
- 六、订阅端 worker 的 LSN 变量
- 七、完整 LSN 推进时序:一次 UPDATE 事务
- 八、关键 LSN 推进的精确时机
- 九、LSN 的”取大”与”取小”语义
- 十、异常情况下的 LSN 回退
- 十一、源码速查表
- 十二、参考
一、LSN 基础与全局概念
1.1 XLogRecPtr / pg_lsn 类型
/* xlogdefs.h */
typedef uint64 XLogRecPtr;
/* pg_lsn 的 SQL 类型 */
-- pg_lsn = 8 字节无符号整数(64-bit)
-- 格式化为 "高32位/低32位" 字符串,如 "0/16A0F80"
XLogRecPtr 的 typedef 在 src/include/access/xlogdefs.h:21;pg_lsn 是 SQL 层的同构类型(src/include/utils/builtins.h)。
%X/%X 格式化:LSN_FORMAT_ARGS(lsn) 展开为 (uint32)(lsn>>32), (uint32)lsn,所以:
0/16A0F80=0x00000000 << 32 | 0x0016A0F80=0x16A0F80=23,823,7441/7000060=0x1 << 32 | 0x07000060=4294967296 + 117440608= 实际上 LSN 跨越了第一个 4GB 边界
1.2 LSN 的”指针”语义
XLogRecPtr 是”指向 WAL 字节流的指针”:
LSN X表示”WAL 流的第 X 个字节的位置”XLogRecPtrIsInvalid(lsn)=lsn == 0表示”未设置”- 比较操作直接走
uint64数值比较
1.3 几个核心 LSN 概念
| 概念 | 含义 |
|---|---|
| Insert LSN | 正在插入 WAL 的当前 LSN(由 backend 写 WAL 时推进) |
| Flush LSN | 已 fsync 到磁盘的最大 LSN |
| Read LSN | walsender 当前正在读的位置 |
| Sent LSN | 已发给订阅者的最大 LSN |
| Apply LSN | 订阅者已 apply 的最大 LSN |
| Confirm LSN | 订阅者通过 pg_stat_replication 反馈的”已 apply”位置 |
关键不变量(理想情况下):Insert LSN >= Flush LSN >= Read LSN >= Send LSN >= Apply LSN
二、全链路 LSN 推进全景图
三、WAL 内部的 LSN 物理布局
3.1 WAL 文件结构
pg_wal/
├── 000000010000000000000001 <- segment 1, 16MB
├── 000000010000000000000002 <- segment 2
├── 000000010000000000000003 <- segment 3
└── ...
每个 segment 16MB(wal_segment_size,默认)。段文件名编码 LSN 的高地址:
000000010000000000000003表示 timeline 1,起始 LSN0/03000000
3.2 单条 WAL 记录在文件中的布局
段文件 0/03000000 内部偏移:
+--------------------------------+ offset 0
| XLogPageHeaderData (32 字节) | <- 每页头
| xl_pages: 0x0001 |
| xlp_magic: 0xD109 | ("XLOG" magic)
| xlp_info: 0x00 |
| xlp_tli: 0x0001 |
| xlp_pageaddr: 0x03000000 | <- LSN
| ... |
+--------------------------------+ offset 32
| XLogRecord (24 字节) |
| xl_prev: 0x03000000 | <- 前一条记录位置
| xl_tot_len: 53 | <- 总长度
| xl_xid: 600 | <- 事务 xid
| xl_term: 0 |
| xl_info/rmid: ... |
+--------------------------------+ offset 56
| XLogRecord data (29 字节) | <- 实际数据
+--------------------------------+ offset 85
| Block Reference (24 字节) | <- 整页引用
+--------------------------------+
关键 LSN 关系:
xlp_pageaddr= 所在段的起始 LSNXLogRecord起始 LSN =pageaddr + offset_in_pagexl_prev= 前一条记录的 LSN(形成链表)reader->EndRecPtr=StartLSN + xl_tot_len(下一条 LSN)
3.3 Insert/Flush LSN 推进
/* xloginsert.h */
extern XLogRecPtr XLogInsert(RmgrId rmid, uint8 info);
/* xlog.c */
XLogRecPtr XLogFlush(XLogRecPtr record);
声明在 src/include/access/xloginsert.h:48,实现 XLogInsert 在 src/backend/access/transam/xloginsert.c:474;XLogFlush 在 src/backend/access/transam/xlog.c:2777。
Insert 推进:
- 每次
XLogInsert返回新插入记录的 EndRecPtr - 进程内
MyXLogInsert->CurrBytePos推进 - 全局
XLogCtl->Insert->CurrBytePos也推进(共享)
Flush 推进:
XLogFlush(record)调pg_fsyncXLogCtl->lastFlushedLsn推进到 record 末尾- bgwriter 周期(默认 200ms)调一次
XLogBackgroundFlush(src/backend/access/transam/xlog.c:2965)
关键函数:
GetInsertRecPtr()(src/backend/access/transam/xlog.c:6516):全局 Insert LSNGetFlushRecPtr()(src/backend/access/transam/xlog.c:6533):全局 Flush LSNGetRedoRecPtr()(src/backend/access/transam/xlog.c:6471):checkpoint 起点(最老的 redo 记录)
四、复制槽的 LSN 字段详解
4.1 ReplicationSlotPersistentData 的 LSN 字段(src/include/replication/slot.h:70)
// src/include/replication/slot.h:70-137
typedef struct ReplicationSlotPersistentData
{
/* The slot's identifier */
NameData name;
/* database the slot is active on */
Oid database;
/*
* The slot's behaviour when being dropped (or restored after a crash).
*/
ReplicationSlotPersistency persistency;
/*
* xmin horizon for data
*
* NB: This may represent a value that hasn't been written to disk yet;
* see notes for effective_xmin, below.
*/
TransactionId xmin;
/*
* xmin horizon for catalog tuples
*
* NB: This may represent a value that hasn't been written to disk yet;
* see notes for effective_xmin, below.
*/
TransactionId catalog_xmin;
/* oldest LSN that might be required by this replication slot */
XLogRecPtr restart_lsn;
/* RS_INVAL_NONE if valid, or the reason for having been invalidated */
ReplicationSlotInvalidationCause invalidated;
/*
* Oldest LSN that the client has acked receipt for. This is used as the
* start_lsn point in case the client doesn't specify one, and also as a
* safety measure to jump forwards in case the client specifies a
* start_lsn that's further in the past than this value.
*/
XLogRecPtr confirmed_flush;
/*
* LSN at which we enabled two_phase commit for this slot or LSN at which
* we found a consistent point at the time of slot creation.
*/
XLogRecPtr two_phase_at;
/*
* Allow decoding of prepared transactions?
*/
bool two_phase;
/* plugin name */
NameData plugin;
/*
* Was this slot synchronized from the primary server?
*/
char synced;
/*
* Is this a failover slot (sync candidate for standbys)? Only relevant
* for logical slots on the primary server.
*/
bool failover;
} ReplicationSlotPersistentData;
PG 18 的这个结构里没有
invalidation_lsn/invalidation_time——PG 17 起改用一个invalidated枚举(src/include/replication/slot.h:103)表达失效原因,失效 LSN 不再落盘。原文写的xmin字段(src/include/replication/slot.h:89)在 PG 18 仍然存在。
4.2 5 个核心 LSN/xid 字段
| 字段 | 类型 | 位置 | 含义 | 推进者 |
|---|---|---|---|---|
restart_lsn |
XLogRecPtr |
src/include/replication/slot.h:100 |
slot 阻止此点之前 WAL 被回收 | LogicalIncreaseRestartDecodingForSlot(src/backend/replication/logical/logical.c:1841)、ReplicationSlotReserveWal(src/backend/replication/slot.c:1573) |
confirmed_flush |
XLogRecPtr |
src/include/replication/slot.h:111 |
订阅者已 apply 并 confirm 的位置 | LogicalConfirmReceivedLocation(src/backend/replication/logical/logical.c:1917) |
catalog_xmin |
TransactionId |
src/include/replication/slot.h:97 |
防 VACUUM 删 catalog 行的 xid 下限 | ReplicationSlotsComputeRequiredXmin(src/backend/replication/slot.c:1153) |
two_phase_at |
XLogRecPtr |
src/include/replication/slot.h:117 |
2PC 启用点(< 此 LSN 的 prepared 不发) | CreateReplicationSlot / SnapBuildSetTwoPhaseAt(src/backend/replication/logical/snapbuild.c:295) |
invalidated |
ReplicationSlotInvalidationCause |
src/include/replication/slot.h:103 |
失效原因(枚举) | ReplicationSlotMarkDirty(src/backend/replication/slot.c:1111) |
4.3 restart_lsn 推进
推进条件:
- 收到新
xl_running_xacts记录时,有 in-progress 事务:txn->restart_decoding_lsn - 稳态时,无 in-progress 事务:
last_serialized_snapshot
推进函数(src/backend/replication/logical/snapbuild.c:1253):
// src/backend/replication/logical/snapbuild.c:1247-1264
txn = ReorderBufferGetOldestTXN(builder->reorder);
/*
* oldest ongoing txn might have started when we didn't yet serialize
* anything because we hadn't reached a consistent state yet.
*/
if (txn != NULL && txn->restart_decoding_lsn != InvalidXLogRecPtr)
LogicalIncreaseRestartDecodingForSlot(lsn, txn->restart_decoding_lsn);
/*
* No in-progress transaction, can reuse the last serialized snapshot if
* we have one.
*/
else if (txn == NULL &&
builder->reorder->current_restart_decoding_lsn != InvalidXLogRecPtr &&
builder->last_serialized_snapshot != InvalidXLogRecPtr)
LogicalIncreaseRestartDecodingForSlot(lsn,
builder->last_serialized_snapshot);
LogicalIncreaseRestartDecodingForSlot(src/backend/replication/logical/logical.c:1841,不在 slot.c):
- 内部
max(new, current)取大 SpinLockAcquire(&slot->mutex)slot->data.restart_lsn = max(slot->data.restart_lsn, lsn)(注意:这里的lsn是入参,可能是new_value)
// src/backend/replication/logical/logical.c:1852-1872
SpinLockAcquire(&slot->mutex);
/* don't overwrite if have a newer restart lsn */
if (restart_lsn <= slot->data.restart_lsn)
{
SpinLockRelease(&slot->mutex);
}
/*
* We might have already flushed far enough to directly accept this lsn,
* in this case there is no need to check for existing candidate LSNs
*/
else if (current_lsn <= slot->data.confirmed_flush)
{
slot->candidate_restart_valid = current_lsn;
slot->candidate_restart_lsn = restart_lsn;
SpinLockRelease(&slot->mutex);
/* our candidate can directly be used */
updated_lsn = true;
}
关键不变量:restart_lsn 从不回退(只在原值上 max)
4.4 confirmed_flush 推进
推进条件:订阅者通过 standby_status_update 消息反馈
walsender 处理(src/backend/replication/walsender.c:2455 的 ProcessStandbyReplyMessage):
// src/backend/replication/walsender.c:2473-2477
writePtr = pq_getmsgint64(&reply_message);
flushPtr = pq_getmsgint64(&reply_message);
applyPtr = pq_getmsgint64(&reply_message);
replyTime = pq_getmsgint64(&reply_message);
replyRequested = pq_getmsgbyte(&reply_message);
LogicalConfirmReceivedLocation(src/backend/replication/logical/logical.c:1917):
// src/backend/replication/logical/logical.c:1945-1946
if (lsn > MyReplicationSlot->data.confirmed_flush)
MyReplicationSlot->data.confirmed_flush = lsn;
关键不变量:confirmed_flush >= restart_lsn(否则重启会找不到起点)
4.5 catalog_xmin 推进
推进条件:ReplicationSlotsComputeRequiredXmin(src/backend/replication/slot.c:1153,定期 / 提交时调)
/* 取所有 slot 的 candidate_catalog_xmin 最大值 */
agg_catalog_xmin = max(all slots' candidate_catalog_xmin);
GetOldestSafeDecodingTransactionId(src/backend/storage/ipc/procarray.c:2950):
- 遍历所有运行中的 xid
- 返回
oldestRunningXid或InvalidTransactionId(无 running)
4.6 slot 数据结构(运行时)额外的 LSN
运行时结构 ReplicationSlot 在 src/include/replication/slot.h:155:
/* 在运行时结构(不在 persistent) */
typedef struct ReplicationSlot
{
ReplicationSlotPersistentData data;
/* ... */
XLogRecPtr candidate_xmin_lsn; /* 候选 xmin 的 LSN */
XLogRecPtr candidate_restart_lsn; /* 候选 restart_lsn */
XLogRecPtr candidate_restart_valid; /* 何时该候选生效 */
XLogRecPtr last_saved_confirmed_flush;
XLogRecPtr last_saved_restart_lsn;
} ReplicationSlot;
对应的真实位置:candidate_xmin_lsn 在 src/include/replication/slot.h:201,candidate_restart_valid 在 src/include/replication/slot.h:202,
candidate_restart_lsn 在 src/include/replication/slot.h:203,last_saved_confirmed_flush 在 src/include/replication/slot.h:210,last_saved_restart_lsn 在 src/include/replication/slot.h:224。
PG 18 的
ReplicationSlot里没有invalidate_on_rollback_at这个字段——失效原因只有data.invalidated一个枚举。
这些是候选值,在事务 commit 时被 atomic promote 到 data。
五、walsender 的 LSN 变量详解
5.1 静态变量与 WalSnd 结构
/* src/backend/replication/walsender.c */
static XLogRecPtr sentPtr = InvalidXLogRecPtr; /* 已发到网络 */
static XLogRecPtr sendTimeLineValidUpto = InvalidXLogRecPtr;
static XLogRecPtr flushPtr = InvalidXLogRecPtr; /* 本地静态缓存 */
/* WalSnd 结构(共享内存) */
typedef struct WalSnd
{
XLogRecPtr sentPtr; /* 已发 WAL 的位置 */
XLogRecPtr write; /* 订阅者反馈的已 write 位置 */
XLogRecPtr flush; /* 订阅者反馈的已 flush 位置 */
XLogRecPtr apply; /* 订阅者反馈的已 apply 位置 */
bool needreload; /* 段文件需要重新打开 */
} WalSnd;
真实位置:sentPtr 在 src/backend/replication/walsender.c:170,sendTimeLineValidUpto 在 src/backend/replication/walsender.c:164,flushPtr(函数内 static)在 src/backend/replication/walsender.c:3471;
共享内存结构 WalSnd 定义在 src/include/replication/walsender_private.h:41。
5.2 8 个关键 LSN(walsender 视角)
| LSN | 含义 | 推进者 | 时机 |
|---|---|---|---|
sentPtr(静态) |
walsender 已发到网络的最大 LSN | XLogSendLogical(src/backend/replication/walsender.c:3460) / XLogSendPhysical(src/backend/replication/walsender.c:3150) |
每次发送数据后 |
reader->ReadRecPtr |
XLogReader 当前正在读的 LSN | XLogReadRecord(src/backend/access/transam/xlogreader.c:393) |
每读一条 record |
reader->EndRecPtr |
当前 record 的结束 LSN | XLogReadRecord |
每读一条 record |
reader->PrevRecPtr |
前一条 record 的 LSN | XLogReadRecord |
每读一条 record |
XLogRecPtr lastLsnInRecord |
LogicalDecodingContext 内的当前 record 起始 LSN | LogicalDecodingProcessRecord(src/backend/replication/logical/decode.c:88) |
每处理一条 |
MyWalSnd->sentPtr |
共享内存中已发位置 | sentPtr 同步 |
每次发送 |
MyWalSnd->write/flush/apply |
订阅者反馈 | ProcessStandbyReplyMessage(src/backend/replication/walsender.c:2455) |
收到 standby status update |
WalSndCaughtUp (bool) |
walsender 是否”追上”了 publisher | WalSndWaitForWal(src/backend/replication/walsender.c:1843) |
等待新 WAL 时 |
5.3 sentPtr 推进的关键代码
物理发送(XLogSendPhysical,src/backend/replication/walsender.c:3150):
// src/backend/replication/walsender.c:3434-3443
sentPtr = endptr;
/* Update shared memory status */
{
WalSnd *walsnd = MyWalSnd;
SpinLockAcquire(&walsnd->mutex);
walsnd->sentPtr = sentPtr;
SpinLockRelease(&walsnd->mutex);
}
逻辑发送(XLogSendLogical,src/backend/replication/walsender.c:3460):
// src/backend/replication/walsender.c:3495-3505
LogicalDecodingProcessRecord(logical_decoding_ctx, logical_decoding_ctx->reader);
sentPtr = logical_decoding_ctx->reader->EndRecPtr;
}
/*
* If first time through in this session, initialize flushPtr. Otherwise,
* we only need to update flushPtr if EndRecPtr is past it.
*/
if (flushPtr == InvalidXLogRecPtr ||
logical_decoding_ctx->reader->EndRecPtr >= flushPtr)
5.4 WalSndPrepareWrite / WalSndWriteData 中的 LSN
src/backend/replication/walsender.c:1570(在 walsender.c,不在 logical.c):
// src/backend/replication/walsender.c:1569-1587
static void
WalSndPrepareWrite(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid, bool last_write)
{
/* can't have sync rep confused by sending the same LSN several times */
if (!last_write)
lsn = InvalidXLogRecPtr;
resetStringInfo(ctx->out);
pq_sendbyte(ctx->out, 'w');
pq_sendint64(ctx->out, lsn); /* dataStart */
pq_sendint64(ctx->out, lsn); /* walEnd */
/*
* Fill out the sendtime later, just as it's done in XLogSendPhysical, but
* reserve space here.
*/
pq_sendint64(ctx->out, 0); /* sendtime */
}
关键观察:
last_write = true时:lsn是当前正在发送的 record LSNlast_write = false时:lsn = InvalidXLogRecPtr—— 中途写的数据不计入 sync rep 反馈- 只有 transaction commit 的
lsn会触发MyWalSnd->write/flush/apply推进
WalSndWriteData(src/backend/replication/walsender.c:1597)实际写 pq_putmessage_noblock('d', ...),把缓冲数据发到网络(src/backend/replication/walsender.c:1614)。
PG 18 的插件侧写接口换成了
LogicalOutputPluginWriterPrepareWrite/LogicalOutputPluginWriterWrite/LogicalOutputPluginWriterUpdateProgress(src/include/replication/logical.h:19-31),LogicalDecodingContext里对应三个回调字段在src/include/replication/logical.h:64-66;walsender 侧的实现就是上面这三个WalSnd*函数,由src/backend/replication/logical/logical.c:198的StartupDecodingContext传进去。
5.5 WalSndUpdateProgress 中的 LSN
src/backend/replication/walsender.c:1693:
// src/backend/replication/walsender.c:1692-1715
static void
WalSndUpdateProgress(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid,
bool skipped_xact)
{
static TimestampTz sendTime = 0;
TimestampTz now = GetCurrentTimestamp();
bool pending_writes = false;
bool end_xact = ctx->end_xact;
/*
* Track lag no more than once per WALSND_LOGICAL_LAG_TRACK_INTERVAL_MS to
* avoid flooding the lag tracker when we commit frequently.
*
* We don't have a mechanism to get the ack for any LSN other than end
* xact LSN from the downstream. So, we track lag only for end of
* transaction LSN.
*/
#define WALSND_LOGICAL_LAG_TRACK_INTERVAL_MS 1000
if (end_xact && TimestampDifferenceExceeds(sendTime, now,
WALSND_LOGICAL_LAG_TRACK_INTERVAL_MS))
{
LagTrackerWrite(lsn, now);
sendTime = now;
}
关键点:end_xact = true 才更新 lag tracker —— 避免每次空 change 都污染 lag 数据。
5.6 XLogSendLogical 的完整 LSN 推进流程
5.7 MyWalSnd->write/flush/apply 推进
ProcessStandbyReplyMessage(src/backend/replication/walsender.c:2455):
// src/backend/replication/walsender.c:2532-2543
SpinLockAcquire(&walsnd->mutex);
walsnd->write = writePtr;
walsnd->flush = flushPtr;
walsnd->apply = applyPtr;
if (writeLag != -1 || clearLagTimes)
walsnd->writeLag = writeLag;
if (flushLag != -1 || clearLagTimes)
walsnd->flushLag = flushLag;
if (applyLag != -1 || clearLagTimes)
walsnd->applyLag = applyLag;
walsnd->replyTime = replyTime;
SpinLockRelease(&walsnd->mutex);
反馈到复制槽在 src/backend/replication/walsender.c:2552:
// src/backend/replication/walsender.c:2552-2558
if (MyReplicationSlot && flushPtr != InvalidXLogRecPtr)
{
if (SlotIsLogical(MyReplicationSlot))
LogicalConfirmReceivedLocation(flushPtr);
else
PhysicalConfirmReceivedLocation(flushPtr);
}
关键观察:write/flush/apply 都是订阅者自己说的 —— walsender 不验证。
5.8 sentPtr 与 MyWalSnd->sentPtr 的关系
/* 静态 sentPtr(本地变量) */
static XLogRecPtr sentPtr;
/* 与共享内存的同步 */
SpinLockAcquire(&MyWalSnd->mutex);
MyWalSnd->sentPtr = sentPtr;
SpinLockRelease(&MyWalSnd->mutex);
真实位置:src/backend/replication/walsender.c:3537(逻辑发送路径)与 src/backend/replication/walsender.c:3440(物理发送路径)。
触发同步的时机:WalSndLoop 每次循环末尾,或 ProcessRepliesIfAny。
六、订阅端 worker 的 LSN 变量
6.1 worker 的 LSN 字段
src/include/replication/worker_internal.h:37(结构体定义在头文件里,不在 worker.c):
typedef struct LogicalRepWorker
{
Oid subid;
Oid relid;
char originname[NAMEDATALEN];
XLogRecPtr last_lsn; /* 重点:已处理的最后 LSN */
XLogRecPtr reply_lsn; /* 上次回写给 walsender 的 LSN */
} LogicalRepWorker;
真实位置:last_lsn 在 src/include/replication/worker_internal.h:90,reply_lsn 在 src/include/replication/worker_internal.h:93。
6.2 4 个 LSN 字段
| 字段 | 含义 | 推进 |
|---|---|---|
MyLogicalRepWorker->last_lsn |
worker 内部已处理位置 | UpdateWorkerStats(src/backend/replication/logical/worker.c:3596) |
MyLogicalRepWorker->reply_lsn |
已回写给 walsender 的位置 | UpdateWorkerStats(src/backend/replication/logical/worker.c:3596) |
replorigin_session_origin_lsn |
当前 origin 的 LSN | replorigin_session_origin(src/backend/replication/logical/worker.c:2301) |
commit_data.commit_lsn (临时) |
当前事务 commit 消息里的 LSN | 解析 msg(src/backend/replication/logical/proto.c:107) |
6.3 last_lsn / reply_lsn 推进
UpdateWorkerStats(src/backend/replication/logical/worker.c:3596):
// src/backend/replication/logical/worker.c:3595-3606
static void
UpdateWorkerStats(XLogRecPtr last_lsn, TimestampTz send_time, bool reply)
{
MyLogicalRepWorker->last_lsn = last_lsn;
MyLogicalRepWorker->last_send_time = send_time;
MyLogicalRepWorker->last_recv_time = GetCurrentTimestamp();
if (reply)
{
MyLogicalRepWorker->reply_lsn = last_lsn;
MyLogicalRepWorker->reply_time = send_time;
}
}
PG 18 的
UpdateWorkerStats不再持有relmutex自旋锁——PG 17 起 worker 的统计字段只在本进程内写(relmutex字段还留在src/include/replication/worker_internal.h:67,但worker.c里已经没有任何SpinLockAcquire(&MyLogicalRepWorker->relmutex)调用)。
调用时机:每次 worker 处理完一条 message 调一次
6.4 worker 处理消息时的 LSN 推进
/* apply_dispatch */
case 'C': /* COMMIT */
/* commit_data->commit_lsn */
/* commit_data->end_lsn */
apply_handle_commit(xid, commit_data);
/* ... */
UpdateWorkerStats(commit_data->end_lsn, send_time, force_reply);
break;
关键 LSN:
commit_data->commit_lsn:订阅者拿到这个值后,apply 完后发 feedback msg(解析在src/backend/replication/logical/proto.c:107)commit_data->end_lsn:change 流的末尾 LSN(解析在src/backend/replication/logical/proto.c:108)
6.5 worker 反馈(write/flush/apply)
worker 用 send_feedback(src/backend/replication/logical/worker.c:3876)把三个 LSN 回给 walsender:
// src/backend/replication/logical/worker.c:3937-3942
pq_sendbyte(reply_message, 'r');
pq_sendint64(reply_message, recvpos); /* write */
pq_sendint64(reply_message, flushpos); /* flush */
pq_sendint64(reply_message, writepos); /* apply */
pq_sendint64(reply_message, now); /* sendTime */
pq_sendbyte(reply_message, requestReply); /* replyRequested */
注意:write/flush/apply 三者在订阅者端都可能是同一个值(物理复制时 walreceiver 区分三者,逻辑复制 worker 通常 write=flush=apply=last_lsn)。
没有未决事务时,src/backend/replication/logical/worker.c:3907 直接把 flushpos = writepos = recvpos。
七、完整 LSN 推进时序:一次 UPDATE 事务
7.1 场景设定
- publisher 客户端:
UPDATE t SET val=100 WHERE id=1 - t 表:有主键
- xid = 600
- publisher 当前 Flush LSN =
0/1500000 - slot 已存在,
restart_lsn = 0/1500000、confirmed_flush = 0/14FFFF0
7.2 端到端 LSN 推进时序
7.3 LSN 推进时序表
| 步骤 | 事件 | Insert LSN | Flush LSN | sentPtr | confirmed_flush | restart_lsn |
|---|---|---|---|---|---|---|
| 0 | 初始 | 0/1500000 | 0/1500000 | 0/14FFFF0 | 0/14FFFF0 | 0/1500000 |
| 1 | XLogInsert UPDATE | 0/150013C | 0/1500000 | 0/14FFFF0 | 0/14FFFF0 | 0/1500000 |
| 2 | XLogInsert COMMIT | 0/1500158 | 0/1500000 | 0/14FFFF0 | 0/14FFFF0 | 0/1500000 |
| 3 | bgwriter flush | 0/1500158 | 0/1500158 | 0/14FFFF0 | 0/14FFFF0 | 0/1500000 |
| 4 | XLogReadRecord (UPDATE) | 0/1500158 | 0/1500158 | 0/14FFFF0 | 0/14FFFF0 | 0/1500000 |
| 5 | XLogReadRecord (COMMIT) | 0/1500158 | 0/1500158 | 0/14FFFF0 | 0/14FFFF0 | 0/1500000 |
| 6 | WalSndPrepareWrite | 0/1500158 | 0/1500158 | 0/1500158 | 0/14FFFF0 | 0/1500000 |
| 7 | worker 收到 + apply | 0/1500158 | 0/1500158 | 0/1500158 | 0/14FFFF0 | 0/1500000 |
| 8 | worker 发 feedback | 0/1500158 | 0/1500158 | 0/1500158 | 0/1500158 | 0/1500000 |
| 9 | LogicalConfirmReceivedLocation | 0/1500158 | 0/1500158 | 0/1500158 | 0/1500158 | 0/1500000 |
| 10 | 下次 running_xacts | 0/1500158 | 0/1500158 | 0/1500158 | 0/1500158 | 0/1500158 |
八、关键 LSN 推进的精确时机
8.1 推进时机矩阵
| LSN | 推进函数 | 触发时机 | 锁 |
|---|---|---|---|
| Insert LSN | XLogInsert 内部(src/backend/access/transam/xloginsert.c:474) |
每次 backend 写 WAL | 短时间 WALInsertLock |
| Flush LSN | XLogFlush(src/backend/access/transam/xlog.c:2777) |
显式调用 / bgwriter 周期 | WALWriteLock |
reader->ReadRecPtr |
XLogReadRecord(src/backend/access/transam/xlogreader.c:393) |
walsender 每次读 record | 无 |
reader->EndRecPtr |
XLogReadRecord |
同上 | 无 |
sentPtr (静态) |
XLogSendLogical(src/backend/replication/walsender.c:3460)/XLogSendPhysical(src/backend/replication/walsender.c:3150) |
每次发送 | 无 |
MyWalSnd->sentPtr |
发送路径同步(src/backend/replication/walsender.c:3538) |
每次发送 | MyWalSnd->mutex |
MyWalSnd->write/flush/apply |
ProcessStandbyReplyMessage(src/backend/replication/walsender.c:2455) |
收到 feedback | MyWalSnd->mutex |
slot->data.restart_lsn |
LogicalIncreaseRestartDecodingForSlot(src/backend/replication/logical/logical.c:1841) |
每次 running_xacts + CheckPointSnapBuild | slot->mutex |
slot->data.confirmed_flush |
LogicalConfirmReceivedLocation(src/backend/replication/logical/logical.c:1917) |
收到 feedback | slot->mutex |
slot->data.catalog_xmin |
ReplicationSlotsComputeRequiredXmin(src/backend/replication/slot.c:1153) |
提交时 / 显式调 | ReplicationSlotControlLock + ProcArrayLock |
MyLogicalRepWorker->last_lsn |
UpdateWorkerStats(src/backend/replication/logical/worker.c:3596) |
worker 处理完每条 msg | 无(PG 17 起不再持锁) |
MyLogicalRepWorker->reply_lsn |
UpdateWorkerStats(reply=true) |
worker 发 feedback 时 | 无(PG 17 起不再持锁) |
8.2 LSN 推进的并发性
多 backend 并发写 WAL:XLogInsert 串行化(同一时间只有一个 backend 在 insert)
walsender 读 与 backend 写并发(读已 flush 的 LSN)
worker 反馈 与 walsender 发送并发(双向 TCP)
8.3 关键的”取大”语义
LogicalIncreaseXminForSlot(src/backend/replication/logical/logical.c:1773,不在 slot.c):
// src/backend/replication/logical/logical.c:1783-1822
SpinLockAcquire(&slot->mutex);
/*
* don't overwrite if we already have a newer xmin. This can happen if we
* restart decoding in a slot.
*/
if (TransactionIdPrecedesOrEquals(xmin, slot->data.catalog_xmin))
{
}
/*
* If the client has already confirmed up to this lsn, we directly can
* mark this as accepted. This can happen if we restart decoding in a
* slot.
*/
else if (current_lsn <= slot->data.confirmed_flush)
{
slot->candidate_catalog_xmin = xmin;
slot->candidate_xmin_lsn = current_lsn;
/* our candidate can directly be used */
updated_xmin = true;
}
/*
* Only increase if the previous values have been applied, otherwise we
* might never end up updating if the receiver acks too slowly.
*/
else if (slot->candidate_xmin_lsn == InvalidXLogRecPtr)
{
slot->candidate_catalog_xmin = xmin;
slot->candidate_xmin_lsn = current_lsn;
/*
* Log new xmin at an appropriate log level after releasing the
* spinlock.
*/
got_new_xmin = true;
}
SpinLockRelease(&slot->mutex);
LogicalConfirmReceivedLocation(src/backend/replication/logical/logical.c:1917):
// src/backend/replication/logical/logical.c:1945-1946
if (lsn > MyReplicationSlot->data.confirmed_flush)
MyReplicationSlot->data.confirmed_flush = lsn;
LogicalIncreaseRestartDecodingForSlot(src/backend/replication/logical/logical.c:1841):
// src/backend/replication/logical/logical.c:1854-1858
/* don't overwrite if have a newer restart lsn */
if (restart_lsn <= slot->data.restart_lsn)
{
SpinLockRelease(&slot->mutex);
}
ReplicationSlotMarkDirty(src/backend/replication/slot.c:1111):
// src/backend/replication/slot.c:1117-1120
SpinLockAcquire(&slot->mutex);
MyReplicationSlot->just_dirtied = true;
MyReplicationSlot->dirty = true;
SpinLockRelease(&slot->mutex);
ReplicationSlotSave(src/backend/replication/slot.c:1093):
// src/backend/replication/slot.c:1097-1100
Assert(MyReplicationSlot != NULL);
sprintf(path, "%s/%s", PG_REPLSLOT_DIR, NameStr(MyReplicationSlot->data.name));
SaveSlotToPath(MyReplicationSlot, path, ERROR);
UpdateWorkerStats(src/backend/replication/logical/worker.c:3596):
// src/backend/replication/logical/worker.c:3598-3600
MyLogicalRepWorker->last_lsn = last_lsn;
MyLogicalRepWorker->last_send_time = send_time;
MyLogicalRepWorker->last_recv_time = GetCurrentTimestamp();
为什么 UpdateWorkerStats 不取大?因为 worker 内部 LSN 是”已经处理完的位置”,天然单调。
九、LSN 的”取大”与”取小”语义
9.1 “取大”(不后退)场景
| LSN | 取大理由 |
|---|---|
slot->data.restart_lsn |
WAL 永远向前,不能回退(slot restart 时要回看) |
slot->data.confirmed_flush |
订阅者反馈必须递增,不能回退 |
slot->effective_xmin |
防止 vacuum 突然激进 |
MyWalSnd->sentPtr |
已发的数据不能”撤回” |
9.2 “取小”场景
MyWalSnd->write/flush/apply:
SpinLockAcquire(&walsnd->mutex);
walsnd->write = writePtr; /* 直接赋值,允许回退 */
SpinLockRelease(&walsnd->mutex);
为什么允许回退?订阅者可能因为某些原因重置了 apply 位置(例如 cascading standby 切换)。
但实际上:sentPtr <= applyPtr 总是成立(walsender 不会发订阅者未 apply 的数据)。
9.3 比较函数
#define XLByteLE(a, b) ((a) <= (b))
#define XLByteLT(a, b) ((a) < (b))
#define XLByteGE(a, b) ((a) >= (b))
#define XLByteGT(a, b) ((a) > (b))
#define XLByteEQ(a, b) ((a) == (b))
这些是简单的 uint64 比较。但注意:XLogRecPtr 跨 4GB 边界时,简单数值比较会错(因为 1/0 < 0/16A0F80)。
安全的比较宏(src/include/access/xlog_internal.h:103):
#define XLogSegNoOffsetToRecPtr(segno, offset, wal_segsz_bytes, dest) ...
按 segment 算的”回环”版本。
十、异常情况下的 LSN 回退
10.1 publisher 崩溃恢复
场景:publisher 崩溃,重启后 redo 之前的 WAL
LSN 变化:
Insert LSN= 从 0 开始,逐步恢复Flush LSN= 从 0 开始slot->data.confirmed_flush= 保留(持久化过)slot->data.restart_lsn= 保留
关键约束:restart_lsn 必须 >= confirmed_flush —— 否则重启时找不到起点
10.2 subscriber 切换
场景:subscriber 从 cascading 切换到直接连接 primary
MyWalSnd->apply 变化:
- 原 cascading:
apply = 0x16A0F80 - 切换后:
apply = 0x14FFFF0(旧的 apply 位置)
PG 行为:applyPtr = pq_getmsgint64,直接覆盖,允许回退
10.3 slot 失效
场景:WAL 被回收(slot 阻止不及),restart_lsn 已经小于实际可读位置
失效原因(src/include/replication/slot.h:51-62):
// src/include/replication/slot.h:51-62
typedef enum ReplicationSlotInvalidationCause
{
RS_INVAL_NONE = 0,
/* required WAL has been removed */
RS_INVAL_WAL_REMOVED = (1 << 0),
/* required rows have been removed */
RS_INVAL_HORIZON = (1 << 1),
/* wal_level insufficient for slot */
RS_INVAL_WAL_LEVEL = (1 << 2),
/* idle slot timeout has occurred */
RS_INVAL_IDLE_TIMEOUT = (1 << 3),
} ReplicationSlotInvalidationCause;
PG 18 的枚举里没有
RS_INVAL_OVERSIZE/RS_INVAL_INCOMPATIBLE_TUPLE/RS_INVAL_INCOMPATIBLE_DB这几个值——超限的 slot 直接报错终止,不走”失效”这条路。
失效时:slot->data.invalidated = RS_INVAL_WAL_REMOVED,restart_lsn 标记为失效。
10.4 crash 后 restart_lsn 的恢复
publisher 写入 WAL 到 0/1500000
publisher 崩溃
publisher 重启
恢复时:
- 扫描所有 .snap 文件
- 找 restart_lsn 对应的 .snap(可能落后于当前最新)
- 从 .snap 加载 SnapBuild 状态
- confirmed_flush 也保留
关键:restart_lsn 持久化在 pg_replslot/<name> 目录下的文件,重启时优先于 confirmed_flush。
十一、源码速查表
11.1 复制槽的 LSN 相关
| 位置 | 字段 | 类型 | 含义 |
|---|---|---|---|
src/include/replication/slot.h:100 |
data.restart_lsn |
XLogRecPtr |
slot 阻止 WAL 回收的最小 LSN |
src/include/replication/slot.h:111 |
data.confirmed_flush |
XLogRecPtr |
订阅者已 apply 位置 |
src/include/replication/slot.h:97 |
data.catalog_xmin |
TransactionId |
catalog 保护 xmin |
src/include/replication/slot.h:117 |
data.two_phase_at |
XLogRecPtr |
2PC 启用 LSN |
src/include/replication/slot.h:181 |
effective_xmin |
TransactionId |
实际生效的 xmin |
src/include/replication/slot.h:182 |
effective_catalog_xmin |
TransactionId |
实际生效 catalog xmin |
src/include/replication/slot.h:201 |
candidate_xmin_lsn |
XLogRecPtr |
候选值 LSN |
src/include/replication/slot.h:203 |
candidate_restart_lsn |
XLogRecPtr |
候选 restart |
src/include/replication/slot.h:202 |
candidate_restart_valid |
XLogRecPtr |
候选生效 LSN |
src/include/replication/slot.h:210 |
last_saved_confirmed_flush |
XLogRecPtr |
上次 save 的位置 |
src/include/replication/slot.h:224 |
last_saved_restart_lsn |
XLogRecPtr |
上次 save 的位置 |
11.2 walsender 的 LSN 变量
| 位置 | 变量 | 含义 |
|---|---|---|
src/backend/replication/walsender.c:170 |
sentPtr(静态) |
已发到网络 |
src/backend/replication/walsender.c:164 |
sendTimeLineValidUpto |
timeline 切换点 |
src/backend/replication/walsender.c:3471 |
flushPtr(静态) |
本地 flush 缓存 |
src/include/replication/walsender_private.h:46 |
WalSnd.sentPtr |
共享内存 sent |
src/include/replication/walsender_private.h:55 |
WalSnd.write |
订阅者 writePtr |
src/include/replication/walsender_private.h:56 |
WalSnd.flush |
订阅者 flushPtr |
src/include/replication/walsender_private.h:57 |
WalSnd.apply |
订阅者 applyPtr |
11.3 订阅端 worker 的 LSN 字段
| 位置 | 字段 | 含义 |
|---|---|---|
src/include/replication/worker_internal.h:90 |
MyLogicalRepWorker->last_lsn |
已处理 LSN |
src/include/replication/worker_internal.h:93 |
MyLogicalRepWorker->reply_lsn |
已反馈 LSN |
src/backend/replication/logical/proto.c:107 |
commit_data.commit_lsn |
msg 里的 commit 位置 |
src/backend/replication/logical/proto.c:108 |
commit_data.end_lsn |
change 流末尾 |
src/backend/replication/logical/proto.c:338 |
rollback_data.rollback_end_lsn |
rollback 位置 |
11.4 关键推进函数
| 函数 | 位置 | 推进 |
|---|---|---|
XLogInsert |
src/backend/access/transam/xloginsert.c:474 |
Insert LSN |
XLogFlush |
src/backend/access/transam/xlog.c:2777 |
Flush LSN |
XLogReadRecord |
src/backend/access/transam/xlogreader.c:393 |
reader.ReadRecPtr / EndRecPtr |
XLogSendLogical |
src/backend/replication/walsender.c:3460 |
sentPtr |
XLogSendPhysical |
src/backend/replication/walsender.c:3150 |
sentPtr |
ProcessStandbyReplyMessage |
src/backend/replication/walsender.c:2455 |
MyWalSnd->write/flush/apply |
LogicalConfirmReceivedLocation |
src/backend/replication/logical/logical.c:1917 |
confirmed_flush |
LogicalIncreaseRestartDecodingForSlot |
src/backend/replication/logical/logical.c:1841 |
restart_lsn |
LogicalIncreaseXminForSlot |
src/backend/replication/logical/logical.c:1773 |
effective_xmin |
ReplicationSlotsComputeRequiredXmin |
src/backend/replication/slot.c:1153 |
catalog_xmin |
UpdateWorkerStats |
src/backend/replication/logical/worker.c:3596 |
last_lsn / reply_lsn |
send_feedback |
src/backend/replication/logical/worker.c:3876 |
反馈 write/flush/apply |
11.5 SQL 视图暴露的 LSN
-- pg_replication_slots
SELECT slot_name,
restart_lsn, -- 启动点
confirmed_flush_lsn, -- 已 apply 位置
catalog_xmin -- catalog 保护 xid
FROM pg_replication_slots;
-- pg_stat_replication
SELECT pid, application_name,
sent_lsn, -- walsender 已发
write_lsn, -- 订阅者 write
flush_lsn, -- 订阅者 flush
replay_lsn, -- 订阅者 apply(也叫 replay)
sync_state
FROM pg_stat_replication;
十二、参考
12.1 源码
- WAL 底层:
src/backend/access/transam/xlog.c:2777(XLogFlush) - WAL 插入:
src/backend/access/transam/xloginsert.c:474(XLogInsert) - WAL Reader:
src/backend/access/transam/xlogreader.c:393(XLogReadRecord) - LSN 类型定义:
src/include/access/xlogdefs.h:21(XLogRecPtr) - 复制槽结构:
src/include/replication/slot.h:70-137(ReplicationSlotPersistentData) - 复制槽运行时结构:
src/include/replication/slot.h:155(ReplicationSlot) - 复制槽操作:
src/backend/replication/slot.c:1093(ReplicationSlotSave) - 逻辑解码协调:
src/backend/replication/logical/logical.c:1917(LogicalConfirmReceivedLocation) - PG18 插件写接口:
src/include/replication/logical.h:19-31(LogicalOutputPluginWriter*) - WAL sender:
src/backend/replication/walsender.c:2455(ProcessStandbyReplyMessage) - 共享内存 WAL snder:
src/include/replication/walsender_private.h:41(WalSnd) - 订阅端 worker:
src/backend/replication/logical/worker.c:3596(UpdateWorkerStats) - 订阅端 worker 结构:
src/include/replication/worker_internal.h:37(LogicalRepWorker) - 复制协议:
src/backend/replication/libpqwalreceiver.c
12.2 站内文章
- PostgreSQL 逻辑复制端到端
- PostgreSQL snapbuild.c 深度解析
- CREATE_REPLICATION_SLOT 端到端
- SnapBuildFindSnapshot 深度拆解
- PostgreSQL 行锁机制深度解析
12.3 官方文档
- pg_lsn 类型
- pg_replication_slots
- pg_stat_replication
- Replication Protocol
- Streaming Replication
- WAL Internals
12.4 关键术语
XLogRecPtr:WAL 字节流中的 64-bit 位置InvalidXLogRecPtr:特指0,表示”未设置”restart_lsn:slot 阻止 WAL 回收的最小 LSN(下次启动点)confirmed_flush:订阅者已 apply 位置sentPtr:walsender 已发位置write/flush/apply:订阅者反馈的三种 LSN(物理复制区分,逻辑复制通常相等)last_lsn/reply_lsn:worker 内部位置last_saved_*:slot 上次 Save 时的位置(用于判断是否 dirty)candidate_*:事务内的候选 LSN(commit 时 promote 到 data)%X/%X:LSN_FORMAT_ARGS格式化为”高32/低32”十六进制
更新日志
- 2026-10-19:初版发布。覆盖 LSN 全链路推进(20+ 个 LSN 变量)、复制槽 11 个 LSN 字段、walsender 8+ 个 LSN 变量、worker 4+ 个 LSN 字段,11 张架构/流程/时序图,一次 UPDATE 事务的 10 步 LSN 推进表。