Branch data Line data Source code
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 : 300 : WaitTargetLSN(XLogRecPtr lsn)
51 : : {
52 : 300 : uint32 page_offset = lsn % XLOG_BLCKSZ;
53 : : uint32 header_size;
54 : :
55 [ + + ]: 300 : if (XLogSegmentOffset(lsn, wal_segment_size) < XLOG_BLCKSZ)
56 : 62 : header_size = SizeOfXLogLongPHD;
57 : : else
58 : 238 : header_size = SizeOfXLogShortPHD;
59 : :
60 [ + + + + ]: 300 : if (page_offset > 0 && page_offset <= header_size)
61 : 5 : return lsn - page_offset;
62 : 295 : return lsn;
63 : : }
64 : :
65 : : void
66 : 304 : ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, bool isTopLevel,
67 : : DestReceiver *dest)
68 : : {
69 : : XLogRecPtr lsn;
70 : : XLogRecPtr target_lsn;
71 : 304 : int timeout = 0;
72 : : WaitLSNResult waitLSNResult;
73 : 304 : WaitLSNType lsnType = WAIT_LSN_TYPE_STANDBY_REPLAY; /* default */
74 : 304 : bool throw = true;
75 : : TupleDesc tupdesc;
76 : : TupOutputState *tstate;
77 : 304 : const char *result = "<unset>";
78 : 304 : bool timeout_specified = false;
79 : 304 : bool no_throw_specified = false;
80 : 304 : 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 [ + + ]: 304 : if (!isTopLevel)
87 [ + - ]: 3 : ereport(ERROR,
88 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
89 : : errmsg("%s can only be executed as a top-level statement",
90 : : "WAIT"),
91 : : errdetail("WAIT cannot be used within a function, procedure, or DO block.")));
92 : :
93 : : /* Parse and validate the mandatory LSN */
94 : 301 : lsn = DatumGetLSN(DirectFunctionCall1(pg_lsn_in,
95 : : CStringGetDatum(stmt->lsn_literal)));
96 : 300 : target_lsn = WaitTargetLSN(lsn);
97 : :
98 [ + + + + : 1373 : foreach_node(DefElem, defel, stmt->options)
+ + ]
99 : : {
100 [ + + ]: 791 : if (strcmp(defel->defname, "mode") == 0)
101 : : {
102 : : char *mode_str;
103 : :
104 [ + + ]: 272 : if (mode_specified)
105 : 1 : errorConflictingDefElem(defel, pstate);
106 : 271 : mode_specified = true;
107 : :
108 : 271 : mode_str = defGetString(defel);
109 : :
110 [ + + ]: 271 : if (pg_strcasecmp(mode_str, "standby_replay") == 0)
111 : 207 : lsnType = WAIT_LSN_TYPE_STANDBY_REPLAY;
112 [ + + ]: 64 : else if (pg_strcasecmp(mode_str, "standby_write") == 0)
113 : 31 : lsnType = WAIT_LSN_TYPE_STANDBY_WRITE;
114 [ + + ]: 33 : else if (pg_strcasecmp(mode_str, "standby_flush") == 0)
115 : 17 : lsnType = WAIT_LSN_TYPE_STANDBY_FLUSH;
116 [ + + ]: 16 : else if (pg_strcasecmp(mode_str, "primary_flush") == 0)
117 : 15 : lsnType = WAIT_LSN_TYPE_PRIMARY_FLUSH;
118 : : else
119 [ + - ]: 1 : ereport(ERROR,
120 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
121 : : errmsg("unrecognized value for %s option \"%s\": \"%s\"",
122 : : "WAIT", defel->defname, mode_str),
123 : : parser_errposition(pstate, defel->location)));
124 : : }
125 [ + + ]: 519 : else if (strcmp(defel->defname, "timeout") == 0)
126 : : {
127 : : char *timeout_str;
128 : : const char *hintmsg;
129 : :
130 [ + + ]: 274 : if (timeout_specified)
131 : 1 : errorConflictingDefElem(defel, pstate);
132 : 273 : timeout_specified = true;
133 : :
134 : 273 : timeout_str = defGetString(defel);
135 : :
136 [ + + ]: 273 : if (!parse_int(timeout_str, &timeout, GUC_UNIT_MS, &hintmsg))
137 [ + - + + ]: 2 : ereport(ERROR,
138 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
139 : : errmsg("invalid timeout value: \"%s\"", timeout_str),
140 : : hintmsg ? errhint("%s", _(hintmsg)) : 0,
141 : : parser_errposition(pstate, defel->location));
142 : :
143 [ + + ]: 271 : if (timeout < 0)
144 [ + - ]: 1 : ereport(ERROR,
145 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
146 : : errmsg("timeout cannot be negative"),
147 : : parser_errposition(pstate, defel->location));
148 : : }
149 [ + + ]: 245 : else if (strcmp(defel->defname, "no_throw") == 0)
150 : : {
151 [ + + ]: 243 : if (no_throw_specified)
152 : 1 : errorConflictingDefElem(defel, pstate);
153 : :
154 : 242 : no_throw_specified = true;
155 : :
156 : 242 : throw = !defGetBoolean(defel);
157 : : }
158 : : else
159 : : {
160 [ + - ]: 2 : ereport(ERROR,
161 : : errcode(ERRCODE_SYNTAX_ERROR),
162 : : errmsg("option \"%s\" not recognized",
163 : : defel->defname),
164 : : parser_errposition(pstate, defel->location));
165 : : }
166 : : }
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 [ - + ]: 291 : 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 : 291 : InvalidateCatalogSnapshot();
187 : :
188 : : /* Give up if there is still an active or registered snapshot. */
189 [ + + ]: 291 : if (HaveRegisteredOrActiveSnapshot())
190 [ + - + + ]: 2 : ereport(ERROR,
191 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
192 : : errmsg("WAIT cannot be executed while the current transaction holds a snapshot"),
193 : : IsolationUsesXactSnapshot() ?
194 : : 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 : : 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 [ + + ]: 289 : if (lsnType == WAIT_LSN_TYPE_PRIMARY_FLUSH)
207 : : {
208 [ + + ]: 15 : if (RecoveryInProgress())
209 [ + - ]: 1 : ereport(ERROR,
210 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
211 : : errmsg("recovery is in progress"),
212 : : errhint("Waiting for primary_flush can only be done on a primary server. "
213 : : "Use standby_flush mode on a standby server.")));
214 : : }
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 [ + + + + ]: 288 : if ((lsnType == WAIT_LSN_TYPE_STANDBY_REPLAY ||
246 [ + + ]: 31 : lsnType == WAIT_LSN_TYPE_STANDBY_WRITE ||
247 [ + + ]: 274 : lsnType == WAIT_LSN_TYPE_STANDBY_FLUSH) &&
248 [ + + ]: 545 : RecoveryInProgress() &&
249 : 271 : target_lsn > GetCurrentLSNForWaitType(lsnType))
250 : : {
251 : : LOCKTAG locktag;
252 : :
253 [ + + ]: 44 : if (GetAnyGrantedHeavyweightLock(&locktag))
254 : : {
255 : : StringInfoData locktagbuf;
256 : :
257 : 2 : initStringInfo(&locktagbuf);
258 : 2 : DescribeLockTag(&locktagbuf, &locktag);
259 : :
260 [ + - ]: 2 : ereport(ERROR,
261 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
262 : : errmsg("cannot wait for a standby LSN while holding locks"),
263 : : errdetail("This session holds a lock on %s, which could make recovery wait for this session while this session waits for recovery.",
264 : : locktagbuf.data),
265 : : errhint("Release the locks, or execute WAIT before acquiring them.")));
266 : : }
267 : : }
268 : :
269 : : /* Now wait for the LSN */
270 : 286 : waitLSNResult = WaitForLSN(lsnType, target_lsn, timeout);
271 : :
272 : : /*
273 : : * Process the result of WaitForLSN(). Throw appropriate error if needed.
274 : : */
275 [ + + + - ]: 285 : switch (waitLSNResult)
276 : : {
277 : 274 : case WAIT_LSN_RESULT_SUCCESS:
278 : : /* Nothing to do on success */
279 : 274 : result = "success";
280 : 274 : break;
281 : :
282 : 6 : case WAIT_LSN_RESULT_TIMEOUT:
283 [ + + ]: 6 : if (throw)
284 : : {
285 : 1 : XLogRecPtr currentLSN = GetCurrentLSNForWaitType(lsnType);
286 : :
287 [ + - - - : 1 : switch (lsnType)
- ]
288 : : {
289 : 1 : case WAIT_LSN_TYPE_STANDBY_REPLAY:
290 [ + - ]: 1 : ereport(ERROR,
291 : : errcode(ERRCODE_QUERY_CANCELED),
292 : : errmsg("timed out while waiting for target LSN %X/%08X to be replayed; current standby_replay LSN %X/%08X",
293 : : LSN_FORMAT_ARGS(lsn),
294 : : LSN_FORMAT_ARGS(currentLSN)));
295 : : break;
296 : :
297 : 0 : case WAIT_LSN_TYPE_STANDBY_WRITE:
298 [ # # ]: 0 : ereport(ERROR,
299 : : errcode(ERRCODE_QUERY_CANCELED),
300 : : errmsg("timed out while waiting for target LSN %X/%08X to be written; current standby_write LSN %X/%08X",
301 : : LSN_FORMAT_ARGS(lsn),
302 : : LSN_FORMAT_ARGS(currentLSN)));
303 : : break;
304 : :
305 : 0 : case WAIT_LSN_TYPE_STANDBY_FLUSH:
306 [ # # ]: 0 : ereport(ERROR,
307 : : errcode(ERRCODE_QUERY_CANCELED),
308 : : errmsg("timed out while waiting for target LSN %X/%08X to be flushed; current standby_flush LSN %X/%08X",
309 : : LSN_FORMAT_ARGS(lsn),
310 : : LSN_FORMAT_ARGS(currentLSN)));
311 : : break;
312 : :
313 : 0 : case WAIT_LSN_TYPE_PRIMARY_FLUSH:
314 [ # # ]: 0 : ereport(ERROR,
315 : : errcode(ERRCODE_QUERY_CANCELED),
316 : : errmsg("timed out while waiting for target LSN %X/%08X to be flushed; current primary_flush LSN %X/%08X",
317 : : LSN_FORMAT_ARGS(lsn),
318 : : LSN_FORMAT_ARGS(currentLSN)));
319 : : break;
320 : :
321 : 0 : default:
322 [ # # ]: 0 : elog(ERROR, "unexpected wait LSN type %d", lsnType);
323 : : }
324 : : }
325 : : else
326 : 5 : result = "timeout";
327 : 5 : break;
328 : :
329 : 5 : case WAIT_LSN_RESULT_NOT_IN_RECOVERY:
330 [ + + ]: 5 : if (throw)
331 : : {
332 [ + + ]: 4 : if (PromoteIsTriggered())
333 : : {
334 : 3 : XLogRecPtr currentLSN = GetCurrentLSNForWaitType(lsnType);
335 : :
336 [ + + + - ]: 3 : switch (lsnType)
337 : : {
338 : 1 : case WAIT_LSN_TYPE_STANDBY_REPLAY:
339 [ + - ]: 1 : ereport(ERROR,
340 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
341 : : errmsg("recovery is not in progress"),
342 : : errdetail("Recovery ended before target LSN %X/%08X was replayed; last standby_replay LSN %X/%08X.",
343 : : LSN_FORMAT_ARGS(lsn),
344 : : LSN_FORMAT_ARGS(currentLSN)));
345 : : break;
346 : :
347 : 1 : case WAIT_LSN_TYPE_STANDBY_WRITE:
348 [ + - ]: 1 : ereport(ERROR,
349 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
350 : : errmsg("recovery is not in progress"),
351 : : errdetail("Recovery ended before target LSN %X/%08X was written; last standby_write LSN %X/%08X.",
352 : : LSN_FORMAT_ARGS(lsn),
353 : : LSN_FORMAT_ARGS(currentLSN)));
354 : : break;
355 : :
356 : 1 : case WAIT_LSN_TYPE_STANDBY_FLUSH:
357 [ + - ]: 1 : ereport(ERROR,
358 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
359 : : errmsg("recovery is not in progress"),
360 : : errdetail("Recovery ended before target LSN %X/%08X was flushed; last standby_flush LSN %X/%08X.",
361 : : LSN_FORMAT_ARGS(lsn),
362 : : LSN_FORMAT_ARGS(currentLSN)));
363 : : break;
364 : :
365 : 0 : default:
366 [ # # ]: 0 : elog(ERROR, "unexpected wait LSN type %d", lsnType);
367 : : }
368 : : }
369 : : else
370 : : {
371 [ - - + - ]: 1 : switch (lsnType)
372 : : {
373 : 0 : case WAIT_LSN_TYPE_STANDBY_REPLAY:
374 [ # # ]: 0 : ereport(ERROR,
375 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
376 : : errmsg("recovery is not in progress"),
377 : : errhint("Waiting for the %s LSN can only be executed during recovery.", "standby_replay"));
378 : : break;
379 : :
380 : 0 : case WAIT_LSN_TYPE_STANDBY_WRITE:
381 [ # # ]: 0 : ereport(ERROR,
382 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
383 : : errmsg("recovery is not in progress"),
384 : : errhint("Waiting for the %s LSN can only be executed during recovery.", "standby_write"));
385 : : break;
386 : :
387 : 1 : case WAIT_LSN_TYPE_STANDBY_FLUSH:
388 [ + - ]: 1 : ereport(ERROR,
389 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
390 : : errmsg("recovery is not in progress"),
391 : : errhint("Waiting for the %s LSN can only be executed during recovery.", "standby_flush"));
392 : : break;
393 : :
394 : 0 : default:
395 [ # # ]: 0 : elog(ERROR, "unexpected wait LSN type %d", lsnType);
396 : : }
397 : : }
398 : : }
399 : : else
400 : 1 : result = "not in recovery";
401 : 1 : break;
402 : : }
403 : :
404 : : /* need a tuple descriptor representing a single TEXT column */
405 : 280 : tupdesc = WaitStmtResultDesc(stmt);
406 : :
407 : : /* prepare for projection of tuples */
408 : 280 : tstate = begin_tup_output_tupdesc(dest, tupdesc, &TTSOpsVirtual);
409 : :
410 : : /* Send it */
411 : 280 : do_text_output_oneline(tstate, result);
412 : :
413 : 280 : end_tup_output(tstate);
414 : 280 : }
415 : :
416 : : TupleDesc
417 : 584 : WaitStmtResultDesc(WaitStmt *stmt)
418 : : {
419 : : 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 : 584 : tupdesc = CreateTemplateTupleDesc(1);
430 : 584 : TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 1, "status",
431 : : TEXTOID, -1, 0);
432 : 584 : TupleDescFinalize(tupdesc);
433 : 584 : return tupdesc;
434 : : }
|