/src/postgres/src/backend/commands/wait.c
Line | Count | Source |
1 | | /*------------------------------------------------------------------------- |
2 | | * |
3 | | * wait.c |
4 | | * Implements WAIT, which allows waiting for events such as |
5 | | * time passing or LSN having been replayed, flushed, or written. |
6 | | * |
7 | | * Portions Copyright (c) 2025-2026, PostgreSQL Global Development Group |
8 | | * |
9 | | * IDENTIFICATION |
10 | | * src/backend/commands/wait.c |
11 | | * |
12 | | *------------------------------------------------------------------------- |
13 | | */ |
14 | | #include "postgres.h" |
15 | | |
16 | | #include "access/xact.h" |
17 | | #include "access/xlog.h" |
18 | | #include "access/xlog_internal.h" |
19 | | #include "access/xlogrecovery.h" |
20 | | #include "access/xlogwait.h" |
21 | | #include "catalog/pg_type_d.h" |
22 | | #include "commands/defrem.h" |
23 | | #include "commands/wait.h" |
24 | | #include "executor/executor.h" |
25 | | #include "parser/parse_node.h" |
26 | | #include "storage/lmgr.h" |
27 | | #include "storage/lock.h" |
28 | | #include "storage/proc.h" |
29 | | #include "utils/builtins.h" |
30 | | #include "utils/guc.h" |
31 | | #include "utils/pg_lsn.h" |
32 | | #include "utils/snapmgr.h" |
33 | | |
34 | | |
35 | | /* |
36 | | * Map a target LSN that points inside or just past a WAL page header to the |
37 | | * start of that page. |
38 | | * |
39 | | * No WAL record can end inside a page header, so both LSNs denote the same |
40 | | * point in the WAL. But when the last record ends exactly at a page |
41 | | * boundary, pg_current_wal_insert_lsn() reports the position after the next |
42 | | * page's header, while the replay, write, and flush positions stay at the |
43 | | * boundary until more WAL is written. Without this mapping, waiting for |
44 | | * such a target would depend on unrelated WAL activity. |
45 | | * |
46 | | * This is done here rather than in WaitForLSN(), whose internal callers |
47 | | * may want to wait for any WAL past a given record end. |
48 | | */ |
49 | | static XLogRecPtr |
50 | | WaitTargetLSN(XLogRecPtr lsn) |
51 | 0 | { |
52 | 0 | uint32 page_offset = lsn % XLOG_BLCKSZ; |
53 | 0 | uint32 header_size; |
54 | |
|
55 | 0 | if (XLogSegmentOffset(lsn, wal_segment_size) < XLOG_BLCKSZ) |
56 | 0 | header_size = SizeOfXLogLongPHD; |
57 | 0 | else |
58 | 0 | header_size = SizeOfXLogShortPHD; |
59 | |
|
60 | 0 | if (page_offset > 0 && page_offset <= header_size) |
61 | 0 | return lsn - page_offset; |
62 | 0 | return lsn; |
63 | 0 | } |
64 | | |
65 | | void |
66 | | ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, bool isTopLevel, |
67 | | DestReceiver *dest) |
68 | 0 | { |
69 | 0 | XLogRecPtr lsn; |
70 | 0 | XLogRecPtr target_lsn; |
71 | 0 | int timeout = 0; |
72 | 0 | WaitLSNResult waitLSNResult; |
73 | 0 | WaitLSNType lsnType = WAIT_LSN_TYPE_STANDBY_REPLAY; /* default */ |
74 | 0 | bool throw = true; |
75 | 0 | TupleDesc tupdesc; |
76 | 0 | TupOutputState *tstate; |
77 | 0 | const char *result = "<unset>"; |
78 | 0 | bool timeout_specified = false; |
79 | 0 | bool no_throw_specified = false; |
80 | 0 | bool mode_specified = false; |
81 | | |
82 | | /* |
83 | | * WAIT must not be run as a non-top-level statement (e.g., inside a |
84 | | * function, procedure, or DO block). Forbid this case upfront. |
85 | | */ |
86 | 0 | if (!isTopLevel) |
87 | 0 | ereport(ERROR, |
88 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
89 | 0 | errmsg("%s can only be executed as a top-level statement", |
90 | 0 | "WAIT"), |
91 | 0 | errdetail("WAIT cannot be used within a function, procedure, or DO block."))); |
92 | | |
93 | | /* Parse and validate the mandatory LSN */ |
94 | 0 | lsn = DatumGetLSN(DirectFunctionCall1(pg_lsn_in, |
95 | 0 | CStringGetDatum(stmt->lsn_literal))); |
96 | 0 | target_lsn = WaitTargetLSN(lsn); |
97 | |
|
98 | 0 | foreach_node(DefElem, defel, stmt->options) |
99 | 0 | { |
100 | 0 | if (strcmp(defel->defname, "mode") == 0) |
101 | 0 | { |
102 | 0 | char *mode_str; |
103 | |
|
104 | 0 | if (mode_specified) |
105 | 0 | errorConflictingDefElem(defel, pstate); |
106 | 0 | mode_specified = true; |
107 | |
|
108 | 0 | mode_str = defGetString(defel); |
109 | |
|
110 | 0 | if (pg_strcasecmp(mode_str, "standby_replay") == 0) |
111 | 0 | lsnType = WAIT_LSN_TYPE_STANDBY_REPLAY; |
112 | 0 | else if (pg_strcasecmp(mode_str, "standby_write") == 0) |
113 | 0 | lsnType = WAIT_LSN_TYPE_STANDBY_WRITE; |
114 | 0 | else if (pg_strcasecmp(mode_str, "standby_flush") == 0) |
115 | 0 | lsnType = WAIT_LSN_TYPE_STANDBY_FLUSH; |
116 | 0 | else if (pg_strcasecmp(mode_str, "primary_flush") == 0) |
117 | 0 | lsnType = WAIT_LSN_TYPE_PRIMARY_FLUSH; |
118 | 0 | else |
119 | 0 | ereport(ERROR, |
120 | 0 | (errcode(ERRCODE_INVALID_PARAMETER_VALUE), |
121 | 0 | errmsg("unrecognized value for %s option \"%s\": \"%s\"", |
122 | 0 | "WAIT", defel->defname, mode_str), |
123 | 0 | parser_errposition(pstate, defel->location))); |
124 | 0 | } |
125 | 0 | else if (strcmp(defel->defname, "timeout") == 0) |
126 | 0 | { |
127 | 0 | char *timeout_str; |
128 | 0 | const char *hintmsg; |
129 | |
|
130 | 0 | if (timeout_specified) |
131 | 0 | errorConflictingDefElem(defel, pstate); |
132 | 0 | timeout_specified = true; |
133 | |
|
134 | 0 | timeout_str = defGetString(defel); |
135 | |
|
136 | 0 | if (!parse_int(timeout_str, &timeout, GUC_UNIT_MS, &hintmsg)) |
137 | 0 | ereport(ERROR, |
138 | 0 | errcode(ERRCODE_INVALID_PARAMETER_VALUE), |
139 | 0 | errmsg("invalid timeout value: \"%s\"", timeout_str), |
140 | 0 | hintmsg ? errhint("%s", _(hintmsg)) : 0, |
141 | 0 | parser_errposition(pstate, defel->location)); |
142 | | |
143 | 0 | if (timeout < 0) |
144 | 0 | ereport(ERROR, |
145 | 0 | errcode(ERRCODE_INVALID_PARAMETER_VALUE), |
146 | 0 | errmsg("timeout cannot be negative"), |
147 | 0 | parser_errposition(pstate, defel->location)); |
148 | 0 | } |
149 | 0 | else if (strcmp(defel->defname, "no_throw") == 0) |
150 | 0 | { |
151 | 0 | if (no_throw_specified) |
152 | 0 | errorConflictingDefElem(defel, pstate); |
153 | |
|
154 | 0 | no_throw_specified = true; |
155 | |
|
156 | 0 | throw = !defGetBoolean(defel); |
157 | 0 | } |
158 | 0 | else |
159 | 0 | { |
160 | 0 | ereport(ERROR, |
161 | 0 | errcode(ERRCODE_SYNTAX_ERROR), |
162 | 0 | errmsg("option \"%s\" not recognized", |
163 | 0 | defel->defname), |
164 | 0 | parser_errposition(pstate, defel->location)); |
165 | 0 | } |
166 | 0 | } |
167 | | |
168 | | /* |
169 | | * We are going to wait for the LSN. We should first care that we don't |
170 | | * hold a snapshot and correspondingly our MyProc->xmin is invalid. |
171 | | * Otherwise, our snapshot could prevent the replay of WAL records |
172 | | * implying a kind of self-deadlock. This is the reason why WAIT is a |
173 | | * command, not a procedure or function. |
174 | | * |
175 | | * Non-top-level contexts are rejected above, but be defensive and pop any |
176 | | * active snapshot if one is present. PortalRunUtility() can tolerate |
177 | | * utility commands that remove the active snapshot. |
178 | | */ |
179 | 0 | if (ActiveSnapshotSet()) |
180 | 0 | PopActiveSnapshot(); |
181 | | |
182 | | /* |
183 | | * At second, invalidate a catalog snapshot if any. And we should be done |
184 | | * with the preparation. |
185 | | */ |
186 | 0 | InvalidateCatalogSnapshot(); |
187 | | |
188 | | /* Give up if there is still an active or registered snapshot. */ |
189 | 0 | if (HaveRegisteredOrActiveSnapshot()) |
190 | 0 | ereport(ERROR, |
191 | 0 | errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), |
192 | 0 | errmsg("WAIT cannot be executed while the current transaction holds a snapshot"), |
193 | 0 | IsolationUsesXactSnapshot() ? |
194 | 0 | errdetail("This transaction runs at an isolation level higher than READ COMMITTED, so it holds a snapshot from its first query until it ends.") : 0); |
195 | | |
196 | | /* |
197 | | * As the result we should hold no snapshot, and correspondingly our xmin |
198 | | * should be unset. |
199 | | */ |
200 | 0 | Assert(MyProc->xmin == InvalidTransactionId); |
201 | | |
202 | | /* |
203 | | * Validate that the requested mode matches the current server state. |
204 | | * Primary modes can only be used on a primary. |
205 | | */ |
206 | 0 | if (lsnType == WAIT_LSN_TYPE_PRIMARY_FLUSH) |
207 | 0 | { |
208 | 0 | if (RecoveryInProgress()) |
209 | 0 | ereport(ERROR, |
210 | 0 | (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), |
211 | 0 | errmsg("recovery is in progress"), |
212 | 0 | errhint("Waiting for primary_flush can only be done on a primary server. " |
213 | 0 | "Use standby_flush mode on a standby server."))); |
214 | 0 | } |
215 | | |
216 | | /* |
217 | | * Conservatively reject an unsatisfied standby LSN wait while this |
218 | | * backend holds a granted heavyweight lock. Recovery may need one of |
219 | | * those locks, directly or through another backend, before replay can |
220 | | * advance far enough to satisfy our wait. This can create a cycle: we |
221 | | * wait for recovery, while recovery waits for us to release the lock. |
222 | | * |
223 | | * However, we do not register our dependency on WAL progress as a lock |
224 | | * wait, so the deadlock detector cannot see the complete cycle. With |
225 | | * unlimited recovery-conflict delays and no other timeout or |
226 | | * cancellation, the cycle can persist indefinitely. |
227 | | * |
228 | | * Write and flush waits can also depend on startup. Without an active |
229 | | * receiver, their replay floor can be their only source of progress, so |
230 | | * holding a lock needed by replay can create the same cycle. |
231 | | * |
232 | | * Streaming can initially provide independent progress, but reception can |
233 | | * stop before the target is reached. Restarting reception requires |
234 | | * startup, and stalled replay prevents further advancement of |
235 | | * restartpoints used to recycle old WAL, so continued reception can |
236 | | * exhaust available space. An active receiver at the start of the wait |
237 | | * therefore does not guarantee that the wait can finish while replay |
238 | | * remains blocked. |
239 | | * |
240 | | * Apply the restriction to all standby modes, including some write and |
241 | | * flush waits that an active receiver could satisfy while locks remain |
242 | | * held. Requests whose target is observed as already reached are exempt |
243 | | * from this restriction. |
244 | | */ |
245 | 0 | if ((lsnType == WAIT_LSN_TYPE_STANDBY_REPLAY || |
246 | 0 | lsnType == WAIT_LSN_TYPE_STANDBY_WRITE || |
247 | 0 | lsnType == WAIT_LSN_TYPE_STANDBY_FLUSH) && |
248 | 0 | RecoveryInProgress() && |
249 | 0 | target_lsn > GetCurrentLSNForWaitType(lsnType)) |
250 | 0 | { |
251 | 0 | LOCKTAG locktag; |
252 | |
|
253 | 0 | if (GetAnyGrantedHeavyweightLock(&locktag)) |
254 | 0 | { |
255 | 0 | StringInfoData locktagbuf; |
256 | |
|
257 | 0 | initStringInfo(&locktagbuf); |
258 | 0 | DescribeLockTag(&locktagbuf, &locktag); |
259 | |
|
260 | 0 | ereport(ERROR, |
261 | 0 | (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), |
262 | 0 | errmsg("cannot wait for a standby LSN while holding locks"), |
263 | 0 | errdetail("This session holds a lock on %s, which could make recovery wait for this session while this session waits for recovery.", |
264 | 0 | locktagbuf.data), |
265 | 0 | errhint("Release the locks, or execute WAIT before acquiring them."))); |
266 | 0 | } |
267 | 0 | } |
268 | | |
269 | | /* Now wait for the LSN */ |
270 | 0 | waitLSNResult = WaitForLSN(lsnType, target_lsn, timeout); |
271 | | |
272 | | /* |
273 | | * Process the result of WaitForLSN(). Throw appropriate error if needed. |
274 | | */ |
275 | 0 | switch (waitLSNResult) |
276 | 0 | { |
277 | 0 | case WAIT_LSN_RESULT_SUCCESS: |
278 | | /* Nothing to do on success */ |
279 | 0 | result = "success"; |
280 | 0 | break; |
281 | | |
282 | 0 | case WAIT_LSN_RESULT_TIMEOUT: |
283 | 0 | if (throw) |
284 | 0 | { |
285 | 0 | XLogRecPtr currentLSN = GetCurrentLSNForWaitType(lsnType); |
286 | |
|
287 | 0 | switch (lsnType) |
288 | 0 | { |
289 | 0 | case WAIT_LSN_TYPE_STANDBY_REPLAY: |
290 | 0 | ereport(ERROR, |
291 | 0 | errcode(ERRCODE_QUERY_CANCELED), |
292 | 0 | errmsg("timed out while waiting for target LSN %X/%08X to be replayed; current standby_replay LSN %X/%08X", |
293 | 0 | LSN_FORMAT_ARGS(lsn), |
294 | 0 | LSN_FORMAT_ARGS(currentLSN))); |
295 | 0 | break; |
296 | | |
297 | 0 | case WAIT_LSN_TYPE_STANDBY_WRITE: |
298 | 0 | ereport(ERROR, |
299 | 0 | errcode(ERRCODE_QUERY_CANCELED), |
300 | 0 | errmsg("timed out while waiting for target LSN %X/%08X to be written; current standby_write LSN %X/%08X", |
301 | 0 | LSN_FORMAT_ARGS(lsn), |
302 | 0 | LSN_FORMAT_ARGS(currentLSN))); |
303 | 0 | break; |
304 | | |
305 | 0 | case WAIT_LSN_TYPE_STANDBY_FLUSH: |
306 | 0 | ereport(ERROR, |
307 | 0 | errcode(ERRCODE_QUERY_CANCELED), |
308 | 0 | errmsg("timed out while waiting for target LSN %X/%08X to be flushed; current standby_flush LSN %X/%08X", |
309 | 0 | LSN_FORMAT_ARGS(lsn), |
310 | 0 | LSN_FORMAT_ARGS(currentLSN))); |
311 | 0 | break; |
312 | | |
313 | 0 | case WAIT_LSN_TYPE_PRIMARY_FLUSH: |
314 | 0 | ereport(ERROR, |
315 | 0 | errcode(ERRCODE_QUERY_CANCELED), |
316 | 0 | errmsg("timed out while waiting for target LSN %X/%08X to be flushed; current primary_flush LSN %X/%08X", |
317 | 0 | LSN_FORMAT_ARGS(lsn), |
318 | 0 | LSN_FORMAT_ARGS(currentLSN))); |
319 | 0 | break; |
320 | | |
321 | 0 | default: |
322 | 0 | elog(ERROR, "unexpected wait LSN type %d", lsnType); |
323 | 0 | } |
324 | 0 | } |
325 | 0 | else |
326 | 0 | result = "timeout"; |
327 | 0 | break; |
328 | | |
329 | 0 | case WAIT_LSN_RESULT_NOT_IN_RECOVERY: |
330 | 0 | if (throw) |
331 | 0 | { |
332 | 0 | if (PromoteIsTriggered()) |
333 | 0 | { |
334 | 0 | XLogRecPtr currentLSN = GetCurrentLSNForWaitType(lsnType); |
335 | |
|
336 | 0 | switch (lsnType) |
337 | 0 | { |
338 | 0 | case WAIT_LSN_TYPE_STANDBY_REPLAY: |
339 | 0 | ereport(ERROR, |
340 | 0 | errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), |
341 | 0 | errmsg("recovery is not in progress"), |
342 | 0 | errdetail("Recovery ended before target LSN %X/%08X was replayed; last standby_replay LSN %X/%08X.", |
343 | 0 | LSN_FORMAT_ARGS(lsn), |
344 | 0 | LSN_FORMAT_ARGS(currentLSN))); |
345 | 0 | break; |
346 | | |
347 | 0 | case WAIT_LSN_TYPE_STANDBY_WRITE: |
348 | 0 | ereport(ERROR, |
349 | 0 | errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), |
350 | 0 | errmsg("recovery is not in progress"), |
351 | 0 | errdetail("Recovery ended before target LSN %X/%08X was written; last standby_write LSN %X/%08X.", |
352 | 0 | LSN_FORMAT_ARGS(lsn), |
353 | 0 | LSN_FORMAT_ARGS(currentLSN))); |
354 | 0 | break; |
355 | | |
356 | 0 | case WAIT_LSN_TYPE_STANDBY_FLUSH: |
357 | 0 | ereport(ERROR, |
358 | 0 | errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), |
359 | 0 | errmsg("recovery is not in progress"), |
360 | 0 | errdetail("Recovery ended before target LSN %X/%08X was flushed; last standby_flush LSN %X/%08X.", |
361 | 0 | LSN_FORMAT_ARGS(lsn), |
362 | 0 | LSN_FORMAT_ARGS(currentLSN))); |
363 | 0 | break; |
364 | | |
365 | 0 | default: |
366 | 0 | elog(ERROR, "unexpected wait LSN type %d", lsnType); |
367 | 0 | } |
368 | 0 | } |
369 | 0 | else |
370 | 0 | { |
371 | 0 | switch (lsnType) |
372 | 0 | { |
373 | 0 | case WAIT_LSN_TYPE_STANDBY_REPLAY: |
374 | 0 | ereport(ERROR, |
375 | 0 | errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), |
376 | 0 | errmsg("recovery is not in progress"), |
377 | 0 | errhint("Waiting for the %s LSN can only be executed during recovery.", "standby_replay")); |
378 | 0 | break; |
379 | | |
380 | 0 | case WAIT_LSN_TYPE_STANDBY_WRITE: |
381 | 0 | ereport(ERROR, |
382 | 0 | errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), |
383 | 0 | errmsg("recovery is not in progress"), |
384 | 0 | errhint("Waiting for the %s LSN can only be executed during recovery.", "standby_write")); |
385 | 0 | break; |
386 | | |
387 | 0 | case WAIT_LSN_TYPE_STANDBY_FLUSH: |
388 | 0 | ereport(ERROR, |
389 | 0 | errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), |
390 | 0 | errmsg("recovery is not in progress"), |
391 | 0 | errhint("Waiting for the %s LSN can only be executed during recovery.", "standby_flush")); |
392 | 0 | break; |
393 | | |
394 | 0 | default: |
395 | 0 | elog(ERROR, "unexpected wait LSN type %d", lsnType); |
396 | 0 | } |
397 | 0 | } |
398 | 0 | } |
399 | 0 | else |
400 | 0 | result = "not in recovery"; |
401 | 0 | break; |
402 | 0 | } |
403 | | |
404 | | /* need a tuple descriptor representing a single TEXT column */ |
405 | 0 | tupdesc = WaitStmtResultDesc(stmt); |
406 | | |
407 | | /* prepare for projection of tuples */ |
408 | 0 | tstate = begin_tup_output_tupdesc(dest, tupdesc, &TTSOpsVirtual); |
409 | | |
410 | | /* Send it */ |
411 | 0 | do_text_output_oneline(tstate, result); |
412 | |
|
413 | 0 | end_tup_output(tstate); |
414 | 0 | } |
415 | | |
416 | | TupleDesc |
417 | | WaitStmtResultDesc(WaitStmt *stmt) |
418 | 0 | { |
419 | 0 | TupleDesc tupdesc; |
420 | | |
421 | | /* |
422 | | * Need a tuple descriptor representing a single TEXT column. |
423 | | * |
424 | | * We use TupleDescInitBuiltinEntry instead of TupleDescInitEntry to avoid |
425 | | * syscache access. This is important because WaitStmtResultDesc may be |
426 | | * called after snapshots have been released, and we must not re-establish |
427 | | * a catalog snapshot which could cause recovery conflicts on a standby. |
428 | | */ |
429 | 0 | tupdesc = CreateTemplateTupleDesc(1); |
430 | 0 | TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 1, "status", |
431 | 0 | TEXTOID, -1, 0); |
432 | 0 | TupleDescFinalize(tupdesc); |
433 | 0 | return tupdesc; |
434 | 0 | } |