pg_walinspect: add functions to locate and list WAL by time and LSN
pg_walinspect: add functions to locate and list WAL by time and LSN
Hi,
I'd like to propose adding two new SQL functions to pg_walinspect.
# Motivation
During HOW2026 in Jinan this April, a DBA talked to me that PG lacks an easy way to locate WAL files by time.
He described a scenario where somebody had done something wrong in a production database, for example accidentally deleting important data. The administrator knew that the incident had happened at around 1am the last night and wanted to confirm what had happened by analyzing WAL.
The problem was that, with thousands of WAL files in pg_wal, where should he start?
# Analysis
After looking into this use case, I think the underlying requirement is slightly different from simply finding a WAL file by timestamp.
Given an approximate point in time, the user really wants an LSN range that is likely to contain the WAL records associated with the operation of interest, for example a DELETE.
PostgreSQL already provides several related facilities:
* pg_ls_waldir() lists WAL files and their modification times.
* pg_split_walfile_name() extracts the segment number and timeline ID from a WAL file name.
* pg_walfile_name() maps an LSN to a WAL file name.
* pg_walinspect can inspect WAL records by LSN.
* pg_waldump can dump WAL records by WAL file or LSN range.
* There are also a number of third-party WAL-mining tools.
However, WAL file modification times don't necessarily reflect the chronological position of the WAL segment. For example, on my local cluster:
```
% ls -l
total 65536
-rw-------@ 1 chaol staff 16777216 Sep 17 16:21 000000010000000000000001
-rw-------@ 1 chaol staff 16777216 Sep 16 13:24 000000010000000000000002
drwx------@ 2 chaol staff 64 Sep 16 13:17 archive_status
drwx------@ 2 chaol staff 64 Sep 16 13:17 summaries
```
Here, segment 1 has a later modification time than segment 2. Since modification times do not necessarily follow WAL segment order, using them to locate the WAL corresponding to a particular point in time can be difficult and sometimes confusing.
So fundamentally, what is missing is an easy way to map a wall-clock time to a useful WAL/LSN range.
# Design
I propose adding two SQL functions.
## pg_get_wal_location_at_time(target_time timestamptz, before interval DEFAULT '1 minute', after interval DEFAULT '1 minute’)
Given a target time and optional before and after intervals, it returns a WAL range around that time.
Not all WAL records contain timestamps, so the implementation reuses the existing timestamp-extraction logic from xlogrecovery.c, exposed by this patch as GetXLogRecordTimestamp(), to identify timestamp-bearing WAL records.
## pg_get_wal_files(start_lsn pg_lsn, end_lsn pg_lsn DEFAULT NULL)
Given a start LSN and an optional end LSN, it returns the WAL files covering that LSN range.
Unlike pg_walfile_name(), which returns only a WAL file name for a single LSN, this function returns each relevant WAL file together with that segment's start and end LSNs.
# Implementation
Both functions are added to the pg_walinspect extension.
There is already quite a bit of reusable WAL-reading infrastructure there, and semantically it also seems like the natural place for this functionality.
The implementation builds on the existing pg_walinspect and XLog reader infrastructure. It does not introduce a new WAL format or a separate WAL parser.
# Demo
For example, suppose I deleted a tuple at around 16:11 yesterday. I can first locate the WAL range around that time:
```
evantest=# SELECT * FROM pg_get_wal_location_at_time('2026-09-17 16:11:08.317383+08', before=>interval '5 minute', after=>interval '5 minute');
start_timestamp | start_lsn | end_timestamp | end_lsn
------------------------------+------------+-----------------------------+------------
2026-09-17 15:57:44.67121+08 | 0/01D05FA0 | 2026-09-18 10:56:13.9463+08 | 0/01D28900
(1 row)
```
Here, you may notice that end_lsn is much later than the specified timestamp plus 5 minutes. I chose this example intentionally.
As mentioned above, not all WAL records carry a timestamp. In this demo database, no timestamp-bearing WAL records were generated for quite some time after the target period, so the next usable timestamp did not appear until today. As a result, the returned WAL range is much wider than the requested five-minute window.
This also illustrates why the function returns an approximate WAL range based on timestamp-bearing records rather than an exact time-to-LSN mapping.
Then I can inspect that LSN range:
```
evantest=# SELECT start_lsn, end_lsn, xid, resource_manager, record_type FROM pg_get_wal_records_info('0/01D05FA0', '0/01D28900') WHERE record_type in ('DELETE', 'COMMIT');
start_lsn | end_lsn | xid | resource_manager | record_type
------------+------------+-----+------------------+-------------
0/01D05FA0 | 0/01D05FC8 | 681 | Transaction | COMMIT
0/01D0B530 | 0/01D0B558 | 682 | Transaction | COMMIT
0/01D0B590 | 0/01D0B5C8 | 683 | Heap | DELETE
0/01D0B5C8 | 0/01D0B5F0 | 683 | Transaction | COMMIT
(4 rows)
```
Now we know the LSN range for the DELETE. If we want to determine which WAL file contains it:
```
evantest=# SELECT * FROM pg_get_wal_files('0/01D0B590', '0/01D0B5C8');
wal_file | segment_start_lsn | segment_end_lsn
--------------------------+-------------------+-----------------
000000010000000000000001 | 0/01000000 | 0/02000000
(1 row)
```
From there, the WAL file can be examined further with pg_waldump or other WAL-mining tools.
PFA v1. Reviews and comments and suggestions are greatly appreciated.
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
Re: pg_walinspect: add functions to locate and list WAL by time and LSN
От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Chao,
Thanks for the patch. I think the use case is real. v1 applies cleanly to current master (dca6a9e320e) and builds
without warnings; the pg_walinspect regression tests pass.
I have some comments below, starting with pg_get_wal_files(),
Regrading pg_get_wal_files():
1. A future end_lsn is rejected, which contradicts what this patch edits.
From the expected output:
SELECT * FROM pg_get_wal_files(pg_current_wal_lsn(), 'FFFFFFFF/FFFFFFFF');
ERROR: WAL start LSN must be less than end LSN
The patch widens the doc tip to "All of the pg_walinspect functions that accept an LSN range are permissive about accepting end_lsn arguments that
are after the server's current LSN", and the next paragraph says FFFFFFFF/FFFFFFFF is equivalent to the current LSN. Neither statement holds here.
Thanks for the patch. I think the use case is real. v1 applies cleanly to current master (dca6a9e320e) and builds
without warnings; the pg_walinspect regression tests pass.
I have some comments below, starting with pg_get_wal_files(),
Regrading pg_get_wal_files():
1. A future end_lsn is rejected, which contradicts what this patch edits.
From the expected output:
SELECT * FROM pg_get_wal_files(pg_current_wal_lsn(), 'FFFFFFFF/FFFFFFFF');
ERROR: WAL start LSN must be less than end LSN
The patch widens the doc tip to "All of the pg_walinspect functions that accept an LSN range are permissive about accepting end_lsn arguments that
are after the server's current LSN", and the next paragraph says FFFFFFFF/FFFFFFFF is equivalent to the current LSN. Neither statement holds here.
The cause is that point_lookup is computed before ValidateInputLSNs() caps end_lsn:
ValidateInputLSNs(start_lsn, &end_lsn);
point_lookup = (start_lsn == end_lsn);
With that order, the extra "start_lsn >= end_lsn" check can go. It also adds a second copy of "WAL start LSN must be less than end LSN", the
message the other thread is changing to "less than or equal to", so dropping it avoids two near-identical messages with different meanings.
2. pg_get_wal_files('0/0', '0/1') reports "WAL segment needed for the requested range is missing" / "Segment 0 is not present in pg_wal".
Segment 0 never exists, so this sends the user looking for a retention problem. The other functions reject the same input with "could not read WAL
at LSN 0/00000000", via the lsn < XLOG_BLCKSZ check in InitXLogReaderState(). The same check would fit here.
Regarding the pg_get_wal_location_at_time():
1. If the upper bound is capped at the current time and no timestamped record exists between target_time - before and now, both anchors resolve to the
same record and the function fails with "could not find a valid WAL range for the requested time window". On a quiet system, asking about something
that happened 30 seconds ago hits this. "Nothing timestamped since then" isn't really an error. Returning the lower anchor with the current flush
LSN as the end seems more useful, even though the docs deliberately avoid building an end boundary from the WAL position. What was the reasoning for that?
2. Regarding the cost, some paths aren't bounded at all. If the lower anchor isn't found, the left scan runs back to the start of the contiguous retained range, and the rescue scan then decodes every segment that remains. So any target older than the retained WAL, such as the clock_timestamp() - interval '100 years' regression test, decodes all of pg_wal only to report "requested time precedes the available WAL range". On a cluster that keeps a lot of WAL, that's a lot of I/O to produce an error. Could the rescue scan be limited, or skipped when the lower anchor can't be found?
Similarly, the "WAL segment needed for the time search is missing" check for a capped upper bound depends only on last_segment and nsegments, which
are known before any decoding. Moving it ahead of the scan avoids a long scan that is certain to end in that error.
A related case: reading the code, if no retained record carries a timestamp at all (a long-running bulk transaction that hasn't committed
yet, for example), the outward scan runs through the whole contiguous range and the function then reports "requested time precedes the
available WAL range", even when target_time is well inside retained WAL. If pg_wal also has a gap, it reports a missing segment instead, though
restoring that segment wouldn't help. This is also the most expensive case, since the whole range has to be decoded to reach it, so a distinct
message such as "no retained WAL record contains a timestamp" would at least tell the user what's actually wrong.
3. Regarding Timelines, GetWalTimeSegments() picks each segment's timeline with tliOfPointInHistory(seg_end, history). Taking the timeline valid at the
segment's end looks right to me: after a promotion, the new timeline's copy of the switch segment contains all WAL up to the switch point. Without
archiving, the old timeline's copy isn't renamed to .partial and stays in pg_wal under the same segment number, so this filter is what keeps the two
apart. However, none of this is exercised. The regression tests run only on timeline 1, and the module has no TAP suite. Given that both the commit
message and the docs claim ranges can cross a timeline switch, I think this needs a TAP test that promotes a standby (with and without archiving).
4. The prepared_ok test and the two RESTORE_POINT checks assert that one specific record is the chosen anchor. Any other timestamped record in the
same window, such as a commit from another session under installcheck or from an autovacuum worker, changes the anchor and fails the test. Checking
that the record type is one of the timestamp-bearing types would be more robust. Also, the four location queries after wal_time_target make the same
call. The fourth query's assertions imply the first three, and the first differs only in passing the intervals positionally, so the second and third can go.
Minor Nits:
1) GetXLogRecordTimestamp() only inspects the decoded record, and none of its logic is specific to recovery. Would xlogreader.c be a better home for it than xlogrecovery.c?
ValidateInputLSNs(start_lsn, &end_lsn);
point_lookup = (start_lsn == end_lsn);
With that order, the extra "start_lsn >= end_lsn" check can go. It also adds a second copy of "WAL start LSN must be less than end LSN", the
message the other thread is changing to "less than or equal to", so dropping it avoids two near-identical messages with different meanings.
2. pg_get_wal_files('0/0', '0/1') reports "WAL segment needed for the requested range is missing" / "Segment 0 is not present in pg_wal".
Segment 0 never exists, so this sends the user looking for a retention problem. The other functions reject the same input with "could not read WAL
at LSN 0/00000000", via the lsn < XLOG_BLCKSZ check in InitXLogReaderState(). The same check would fit here.
Regarding the pg_get_wal_location_at_time():
1. If the upper bound is capped at the current time and no timestamped record exists between target_time - before and now, both anchors resolve to the
same record and the function fails with "could not find a valid WAL range for the requested time window". On a quiet system, asking about something
that happened 30 seconds ago hits this. "Nothing timestamped since then" isn't really an error. Returning the lower anchor with the current flush
LSN as the end seems more useful, even though the docs deliberately avoid building an end boundary from the WAL position. What was the reasoning for that?
2. Regarding the cost, some paths aren't bounded at all. If the lower anchor isn't found, the left scan runs back to the start of the contiguous retained range, and the rescue scan then decodes every segment that remains. So any target older than the retained WAL, such as the clock_timestamp() - interval '100 years' regression test, decodes all of pg_wal only to report "requested time precedes the available WAL range". On a cluster that keeps a lot of WAL, that's a lot of I/O to produce an error. Could the rescue scan be limited, or skipped when the lower anchor can't be found?
Similarly, the "WAL segment needed for the time search is missing" check for a capped upper bound depends only on last_segment and nsegments, which
are known before any decoding. Moving it ahead of the scan avoids a long scan that is certain to end in that error.
A related case: reading the code, if no retained record carries a timestamp at all (a long-running bulk transaction that hasn't committed
yet, for example), the outward scan runs through the whole contiguous range and the function then reports "requested time precedes the
available WAL range", even when target_time is well inside retained WAL. If pg_wal also has a gap, it reports a missing segment instead, though
restoring that segment wouldn't help. This is also the most expensive case, since the whole range has to be decoded to reach it, so a distinct
message such as "no retained WAL record contains a timestamp" would at least tell the user what's actually wrong.
3. Regarding Timelines, GetWalTimeSegments() picks each segment's timeline with tliOfPointInHistory(seg_end, history). Taking the timeline valid at the
segment's end looks right to me: after a promotion, the new timeline's copy of the switch segment contains all WAL up to the switch point. Without
archiving, the old timeline's copy isn't renamed to .partial and stays in pg_wal under the same segment number, so this filter is what keeps the two
apart. However, none of this is exercised. The regression tests run only on timeline 1, and the module has no TAP suite. Given that both the commit
message and the docs claim ranges can cross a timeline switch, I think this needs a TAP test that promotes a standby (with and without archiving).
4. The prepared_ok test and the two RESTORE_POINT checks assert that one specific record is the chosen anchor. Any other timestamped record in the
same window, such as a commit from another session under installcheck or from an autovacuum worker, changes the anchor and fails the test. Checking
that the record type is one of the timestamp-bearing types would be more robust. Also, the four location queries after wal_time_target make the same
call. The fourth query's assertions imply the first three, and the first differs only in passing the intervals positionally, so the second and third can go.
Minor Nits:
1) GetXLogRecordTimestamp() only inspects the decoded record, and none of its logic is specific to recovery. Would xlogreader.c be a better home for it than xlogrecovery.c?
xlogreader.c is also built for frontend programs (pg_waldump compiles it with -DFRONTEND), and the headers it would need, access/xact.h and access/xlog_internal.h, are already included by the
rmgrdesc code that pg_waldump builds. Exporting it from xlogrecovery.c makes it backend-only, so a later time-based filter in pg_waldump, which today has
none, couldn't reuse it.
2) The "duplicate WAL segment in current timeline history" ereport looks unreachable, because the tliOfPointInHistory() filter leaves at most one
file per segment number. It could be an Assert() or elog() rather than a user-facing ERRCODE_DATA_EXCEPTION.
3) GetWalTimeSegments(0, &nsegments, NULL) in pg_get_wal_files() passes a target_time that is never used. Moving the mtime-based candidate selection into its own function would remove that argument.
4) GetWalTimeSegments() repeats GetCurrentLSN()'s flush/replay LSN logic and adds the insert-timeline selection from read_local_xlog_page_guts(). Giving GetCurrentLSN() an optional TLI out-parameter would keep all three in sync.
5) "Preserve the empty-set behavior that STRICT provided for a NULL start": since this is a new function, there's no earlier behavior to preserve.
Finally, pg_get_wal_files() is useful on its own and much closer to ready. Would you consider splitting the two functions into separate patches, so it can move forward while the time-search semantics are worked out?
Regards,
Surya Poondla
rmgrdesc code that pg_waldump builds. Exporting it from xlogrecovery.c makes it backend-only, so a later time-based filter in pg_waldump, which today has
none, couldn't reuse it.
2) The "duplicate WAL segment in current timeline history" ereport looks unreachable, because the tliOfPointInHistory() filter leaves at most one
file per segment number. It could be an Assert() or elog() rather than a user-facing ERRCODE_DATA_EXCEPTION.
3) GetWalTimeSegments(0, &nsegments, NULL) in pg_get_wal_files() passes a target_time that is never used. Moving the mtime-based candidate selection into its own function would remove that argument.
4) GetWalTimeSegments() repeats GetCurrentLSN()'s flush/replay LSN logic and adds the insert-timeline selection from read_local_xlog_page_guts(). Giving GetCurrentLSN() an optional TLI out-parameter would keep all three in sync.
5) "Preserve the empty-set behavior that STRICT provided for a NULL start": since this is a new function, there's no earlier behavior to preserve.
Finally, pg_get_wal_files() is useful on its own and much closer to ready. Would you consider splitting the two functions into separate patches, so it can move forward while the time-search semantics are worked out?
Regards,
Surya Poondla
Re: pg_walinspect: add functions to locate and list WAL by time and LSN
> On Sep 30, 2026, at 06:31, surya poondla wrote:
>
> Hi Chao,
>
> Thanks for the patch. I think the use case is real. v1 applies cleanly to current master (dca6a9e320e) and builds
> without warnings; the pg_walinspect regression tests pass.
Hi Surya,
Thank you so much for being the first reviewer of this patch.
>
> I have some comments below, starting with pg_get_wal_files(),
>
> Regrading pg_get_wal_files():
> 1. A future end_lsn is rejected, which contradicts what this patch edits.
>
> From the expected output:
>
> SELECT * FROM pg_get_wal_files(pg_current_wal_lsn(), 'FFFFFFFF/FFFFFFFF');
> ERROR: WAL start LSN must be less than end LSN
>
> The patch widens the doc tip to "All of the pg_walinspect functions that accept an LSN range are permissive about accepting end_lsn arguments that
> are after the server's current LSN", and the next paragraph says FFFFFFFF/FFFFFFFF is equivalent to the current LSN. Neither statement holds here.
> The cause is that point_lookup is computed before ValidateInputLSNs() caps end_lsn:
>
> ValidateInputLSNs(start_lsn, &end_lsn);
> point_lookup = (start_lsn == end_lsn);
>
> With that order, the extra "start_lsn >= end_lsn" check can go. It also adds a second copy of "WAL start LSN must be less than end LSN", the
> message the other thread is changing to "less than or equal to", so dropping it avoids two near-identical messages with different meanings.
>
Accepted.
> 2. pg_get_wal_files('0/0', '0/1') reports "WAL segment needed for the requested range is missing" / "Segment 0 is not present in pg_wal".
> Segment 0 never exists, so this sends the user looking for a retention problem. The other functions reject the same input with "could not read WAL
> at LSN 0/00000000", via the lsn < XLOG_BLCKSZ check in InitXLogReaderState(). The same check would fit here.
>
Make sense.
>
> Regarding the pg_get_wal_location_at_time():
>
> 1. If the upper bound is capped at the current time and no timestamped record exists between target_time - before and now, both anchors resolve to the
> same record and the function fails with "could not find a valid WAL range for the requested time window". On a quiet system, asking about something
> that happened 30 seconds ago hits this. "Nothing timestamped since then" isn't really an error. Returning the lower anchor with the current flush
> LSN as the end seems more useful, even though the docs deliberately avoid building an end boundary from the WAL position. What was the reasoning for that?
>
> 2. Regarding the cost, some paths aren't bounded at all. If the lower anchor isn't found, the left scan runs back to the start of the contiguous retained range, and the rescue scan then decodes every segment that remains. So any target older than the retained WAL, such as the clock_timestamp() - interval '100 years' regression test, decodes all of pg_wal only to report "requested time precedes the available WAL range". On a cluster that keeps a lot of WAL, that's a lot of I/O to produce an error. Could the rescue scan be limited, or skipped when the lower anchor can't be found?
>
> Similarly, the "WAL segment needed for the time search is missing" check for a capped upper bound depends only on last_segment and nsegments, which
> are known before any decoding. Moving it ahead of the scan avoids a long scan that is certain to end in that error.
>
> A related case: reading the code, if no retained record carries a timestamp at all (a long-running bulk transaction that hasn't committed
> yet, for example), the outward scan runs through the whole contiguous range and the function then reports "requested time precedes the
> available WAL range", even when target_time is well inside retained WAL. If pg_wal also has a gap, it reports a missing segment instead, though
> restoring that segment wouldn't help. This is also the most expensive case, since the whole range has to be decoded to reach it, so a distinct
> message such as "no retained WAL record contains a timestamp" would at least tell the user what's actually wrong.
I thought more about the design and made some significant changes in v2.
First, I switched to binary search for the lower and upper boundaries. I initially avoided this because timestamps of timestamped WAL records are not guaranteed to be ordered monotonically by WAL position. For various reasons, a record with an earlier timestamp can appear later in WAL, so binary search may return an imprecise result. However, considering that (1) large timestamp reordering should be uncommon on production clusters, and (2) the user-specified time range will most likely be an estimate, I think we can tolerate limited timestamp reordering in exchange for decoding significantly less WAL. The search also examines one additional segment in each direction to accommodate limited reordering. If the returned range does not contain the expected records, the user can widen the time range and repeat the search.
Second, when the search finds only one timestamped WAL record within the specified time range, the function no longer fails. Instead, it returns that record’s LSN as both start_lsn and end_lsn.
Third, to simplify the boundary semantics and implementation, the returned boundary timestamps are now within the specified time range. On successful return, start_timestamp is at or after the lower bound, while end_timestamp is at or before the upper bound. Because the search is approximate, the returned records are not guaranteed to be the globally closest timestamped records to those bounds. For example, suppose the requested upper bound is 10:00, and the timestamped records are:
WAL segment 10: 09:55
WAL segment 11: 10:05
WAL segment 12: 10:06
WAL segment 13: 09:59
The binary search may select segment 10 and examine the adjacent segment 11. It would return 09:55 as the upper boundary. However, the globally closest record at or before 10:00 is the 09:59 record in segment 13, which is missed because its timestamp is reordered by more than one segment. As mentioned earlier, this degree of timestamp reordering should be very uncommon on a production cluster. If the user expects the relevant record to be in segment 13, they can widen the upper boundary, for example to 10:10, and repeat the search.
> 3. Regarding Timelines, GetWalTimeSegments() picks each segment's timeline with tliOfPointInHistory(seg_end, history). Taking the timeline valid at the
> segment's end looks right to me: after a promotion, the new timeline's copy of the switch segment contains all WAL up to the switch point. Without
> archiving, the old timeline's copy isn't renamed to .partial and stays in pg_wal under the same segment number, so this filter is what keeps the two
> apart. However, none of this is exercised. The regression tests run only on timeline 1, and the module has no TAP suite. Given that both the commit
> message and the docs claim ranges can cross a timeline switch, I think this needs a TAP test that promotes a standby (with and without archiving).
>
I was straggling whether or not to add a TAP test and ended up not adding one because the module didn’t have other TAP tests. I can add a TAP test for this timeline switch case.
> 4. The prepared_ok test and the two RESTORE_POINT checks assert that one specific record is the chosen anchor. Any other timestamped record in the
> same window, such as a commit from another session under installcheck or from an autovacuum worker, changes the anchor and fails the test. Checking
> that the record type is one of the timestamp-bearing types would be more robust.
Agreed.
> Also, the four location queries after wal_time_target make the same
> call. The fourth query's assertions imply the first three, and the first differs only in passing the intervals positionally, so the second and third can go.
>
Yep, a bit redundant. Removed the fourth.
> Minor Nits:
> 1) GetXLogRecordTimestamp() only inspects the decoded record, and none of its logic is specific to recovery. Would xlogreader.c be a better home for it than xlogrecovery.c?
> xlogreader.c is also built for frontend programs (pg_waldump compiles it with -DFRONTEND), and the headers it would need, access/xact.h and access/xlog_internal.h, are already included by the
> rmgrdesc code that pg_waldump builds. Exporting it from xlogrecovery.c makes it backend-only, so a later time-based filter in pg_waldump, which today has
> none, couldn't reuse it.
Good point. Accepted.
> 2) The "duplicate WAL segment in current timeline history" ereport looks unreachable, because the tliOfPointInHistory() filter leaves at most one
> file per segment number. It could be an Assert() or elog() rather than a user-facing ERRCODE_DATA_EXCEPTION.
Agreed.
> 3) GetWalTimeSegments(0, &nsegments, NULL) in pg_get_wal_files() passes a target_time that is never used. Moving the mtime-based candidate selection into its own function would remove that argument.
Agreed.
> 4) GetWalTimeSegments() repeats GetCurrentLSN()'s flush/replay LSN logic and adds the insert-timeline selection from read_local_xlog_page_guts(). Giving GetCurrentLSN() an optional TLI out-parameter would keep all three in sync.
Agreed.
> 5) "Preserve the empty-set behavior that STRICT provided for a NULL start": since this is a new function, there's no earlier behavior to preserve.
Agreed.
>
> Finally, pg_get_wal_files() is useful on its own and much closer to ready. Would you consider splitting the two functions into separate patches, so it can move forward while the time-search semantics are worked out?
Good suggestion. I have split the two functions into two commits.
PFA v2.
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
Re: pg_walinspect: add functions to locate and list WAL by time and LSN
От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Chao,
Thanks for the quick patch on v2, and for splitting the patch. I checked the changes against my earlier comments, point 1 is fixed (end_lsn is now capped before point_lookup is set), also point 2 (the invalid startLSN message), the timeline TAP test (with archive_mode both off and on), the test robustness changes, the move of GetXLogRecordTimestamp() to
xlogreader.c, and all of the minor items.
v2 applies cleanly to master (10b6e2a3d66) and builds without warnings, and the regression and TAP tests pass.
0001 (pg_get_wal_files) is close. One edge case from reading the code, GetWalTimeSegments() skips segments that start at or after the current LSN.
So if the flush LSN sits exactly on a segment boundary, as on an idle server right after pg_switch_wal(), pg_get_wal_files(pg_current_wal_lsn()) becomes
a point lookup on a filtered-out segment and reports "WAL segment needed for the requested range is missing".
For 0002, I think the change of boundary semantics breaks the main use case. Since v2, start_lsn is the earliest timestamped record found at or after the
lower bound, and end_lsn is the latest found at or before the upper bound. But a transaction's data records come before its commit record in WAL.
Thanks for the quick patch on v2, and for splitting the patch. I checked the changes against my earlier comments, point 1 is fixed (end_lsn is now capped before point_lookup is set), also point 2 (the invalid startLSN message), the timeline TAP test (with archive_mode both off and on), the test robustness changes, the move of GetXLogRecordTimestamp() to
xlogreader.c, and all of the minor items.
v2 applies cleanly to master (10b6e2a3d66) and builds without warnings, and the regression and TAP tests pass.
0001 (pg_get_wal_files) is close. One edge case from reading the code, GetWalTimeSegments() skips segments that start at or after the current LSN.
So if the flush LSN sits exactly on a segment boundary, as on an idle server right after pg_switch_wal(), pg_get_wal_files(pg_current_wal_lsn()) becomes
a point lookup on a filtered-out segment and reports "WAL segment needed for the requested range is missing".
For 0002, I think the change of boundary semantics breaks the main use case. Since v2, start_lsn is the earliest timestamped record found at or after the
lower bound, and end_lsn is the latest found at or before the upper bound. But a transaction's data records come before its commit record in WAL.
So when the commit of the transaction of interest is the first timestamped record in the window, start_lsn is that commit, and the change itself falls
outside the returned range.
I reproduced this with a scratch TAP test: autovacuum off, and no other commits within two seconds of the window.
SELECT clock_timestamp() AS window_start \gset
BEGIN;
SELECT pg_current_wal_insert_lsn() AS delete_lsn \gset
DELETE FROM important WHERE id = 5;
SELECT pg_sleep(0.2);
COMMIT;
SELECT clock_timestamp() AS window_end \gset
SELECT l.start_lsn, l.end_lsn, :'delete_lsn'::pg_lsn AS delete_lsn
FROM pg_get_wal_location_at_time(:'window_start',
interval '500 milliseconds',
:'window_end'::timestamptz -
:'window_start'::timestamptz) AS l;
start_lsn | end_lsn | delete_lsn
------------+------------+------------
0/017EEF78 | 0/017EEF78 | 0/017EEF40
The DELETE ran inside the requested window, and its WAL begins at
0/017EEF40, the insert position taken just before it. Its commit, 56 bytes
later, is the only timestamped record in the window, so it's returned as
both boundaries. Following the documented workflow,
pg_get_wal_records_info(start_lsn, end_lsn) then returns no rows at all,
because that function only emits records that end at or before end_lsn. So
the user sees neither the DELETE nor its commit. On a quiet system, which is
when someone is most likely to be investigating a single mistaken statement,
this is the usual outcome, not a corner case.
Outer anchors (the latest timestamped record at or before the lower bound, and the earliest at or after the upper bound) avoid this, but only with a
fallback for the end. In this reproducer nothing commits after the window, so by my reading v1 would have failed with "requested time follows the
available WAL range" instead. pg_walinspect already treats the current WAL position as a valid end (ValidateInputLSNs() caps end_lsn to it, and the
docs suggest FFFFFFFF/FFFFFFFF for exactly that), so falling back to the current flush/replay LSN, with end_timestamp NULL, seems consistent with the
rest of the module. It would also cover the quiet-system case from my first review.
I don't think the binary search requires inner anchors. It can locate the segment for each bound and then take the outer record from that segment, or
from the nearest earlier (or later) segment that has a timestamped record.
Outer anchors still won't cover a transaction that began before the lower anchor, but the docs already say as much, and it is a much narrower case.
Separately, reading the code, a window that contains no timestamped record,
but has some on both sides, currently ends in "could not find a valid WAL
range for the requested time window" with the detail "The matching lower boundary follows the upper boundary in WAL". That reads like a WAL ordering
problem, when the real cause is that nothing in the window is timestamped.
With outer anchors this case would just return a range.
Regards,
Surya Poondla
outside the returned range.
I reproduced this with a scratch TAP test: autovacuum off, and no other commits within two seconds of the window.
SELECT clock_timestamp() AS window_start \gset
BEGIN;
SELECT pg_current_wal_insert_lsn() AS delete_lsn \gset
DELETE FROM important WHERE id = 5;
SELECT pg_sleep(0.2);
COMMIT;
SELECT clock_timestamp() AS window_end \gset
SELECT l.start_lsn, l.end_lsn, :'delete_lsn'::pg_lsn AS delete_lsn
FROM pg_get_wal_location_at_time(:'window_start',
interval '500 milliseconds',
:'window_end'::timestamptz -
:'window_start'::timestamptz) AS l;
start_lsn | end_lsn | delete_lsn
------------+------------+------------
0/017EEF78 | 0/017EEF78 | 0/017EEF40
The DELETE ran inside the requested window, and its WAL begins at
0/017EEF40, the insert position taken just before it. Its commit, 56 bytes
later, is the only timestamped record in the window, so it's returned as
both boundaries. Following the documented workflow,
pg_get_wal_records_info(start_lsn, end_lsn) then returns no rows at all,
because that function only emits records that end at or before end_lsn. So
the user sees neither the DELETE nor its commit. On a quiet system, which is
when someone is most likely to be investigating a single mistaken statement,
this is the usual outcome, not a corner case.
Outer anchors (the latest timestamped record at or before the lower bound, and the earliest at or after the upper bound) avoid this, but only with a
fallback for the end. In this reproducer nothing commits after the window, so by my reading v1 would have failed with "requested time follows the
available WAL range" instead. pg_walinspect already treats the current WAL position as a valid end (ValidateInputLSNs() caps end_lsn to it, and the
docs suggest FFFFFFFF/FFFFFFFF for exactly that), so falling back to the current flush/replay LSN, with end_timestamp NULL, seems consistent with the
rest of the module. It would also cover the quiet-system case from my first review.
I don't think the binary search requires inner anchors. It can locate the segment for each bound and then take the outer record from that segment, or
from the nearest earlier (or later) segment that has a timestamped record.
Outer anchors still won't cover a transaction that began before the lower anchor, but the docs already say as much, and it is a much narrower case.
Separately, reading the code, a window that contains no timestamped record,
but has some on both sides, currently ends in "could not find a valid WAL
range for the requested time window" with the detail "The matching lower boundary follows the upper boundary in WAL". That reads like a WAL ordering
problem, when the real cause is that nothing in the window is timestamped.
With outer anchors this case would just return a range.
Regards,
Surya Poondla
Re: pg_walinspect: add functions to locate and list WAL by time and LSN
> On Oct 7, 2026, at 07:11, surya poondla wrote: > > Hi Chao, > > Thanks for the quick patch on v2, and for splitting the patch. I checked the changes against my earlier comments, point 1 is fixed (end_lsn is now capped before point_lookup is set), also point 2 (the invalid startLSN message), the timeline TAP test (with archive_mode both off and on), the test robustness changes, the move of GetXLogRecordTimestamp() to > xlogreader.c, and all of the minor items. > > v2 applies cleanly to master (10b6e2a3d66) and builds without warnings, and the regression and TAP tests pass. Thanks again for the follow up review and tests. > > 0001 (pg_get_wal_files) is close. One edge case from reading the code, GetWalTimeSegments() skips segments that start at or after the current LSN. > So if the flush LSN sits exactly on a segment boundary, as on an idle server right after pg_switch_wal(), pg_get_wal_files(pg_current_wal_lsn()) becomes > a point lookup on a filtered-out segment and reports "WAL segment needed for the requested range is missing". Good catch. Fixed in v3. > > For 0002, I think the change of boundary semantics breaks the main use case. Since v2, start_lsn is the earliest timestamped record found at or after the > lower bound, and end_lsn is the latest found at or before the upper bound. But a transaction's data records come before its commit record in WAL. > So when the commit of the transaction of interest is the first timestamped record in the window, start_lsn is that commit, and the change itself falls > outside the returned range. > > I reproduced this with a scratch TAP test: autovacuum off, and no other commits within two seconds of the window. > > SELECT clock_timestamp() AS window_start \gset > BEGIN; > SELECT pg_current_wal_insert_lsn() AS delete_lsn \gset > DELETE FROM important WHERE id = 5; > SELECT pg_sleep(0.2); > COMMIT; > SELECT clock_timestamp() AS window_end \gset > > SELECT l.start_lsn, l.end_lsn, :'delete_lsn'::pg_lsn AS delete_lsn > FROM pg_get_wal_location_at_time(:'window_start', > interval '500 milliseconds', > :'window_end'::timestamptz - > :'window_start'::timestamptz) AS l; > > start_lsn | end_lsn | delete_lsn > ------------+------------+------------ > 0/017EEF78 | 0/017EEF78 | 0/017EEF40 > > The DELETE ran inside the requested window, and its WAL begins at > 0/017EEF40, the insert position taken just before it. Its commit, 56 bytes > later, is the only timestamped record in the window, so it's returned as > both boundaries. Following the documented workflow, > pg_get_wal_records_info(start_lsn, end_lsn) then returns no rows at all, > because that function only emits records that end at or before end_lsn. So > the user sees neither the DELETE nor its commit. On a quiet system, which is > when someone is most likely to be investigating a single mistaken statement, > this is the usual outcome, not a corner case. > > Outer anchors (the latest timestamped record at or before the lower bound, and the earliest at or after the upper bound) avoid this, but only with a > fallback for the end. In this reproducer nothing commits after the window, so by my reading v1 would have failed with "requested time follows the > available WAL range" instead. pg_walinspect already treats the current WAL position as a valid end (ValidateInputLSNs() caps end_lsn to it, and the > docs suggest FFFFFFFF/FFFFFFFF for exactly that), so falling back to the current flush/replay LSN, with end_timestamp NULL, seems consistent with the > rest of the module. It would also cover the quiet-system case from my first review. > > I don't think the binary search requires inner anchors. It can locate the segment for each bound and then take the outer record from that segment, or > from the nearest earlier (or later) segment that has a timestamped record. > Outer anchors still won't cover a transaction that began before the lower anchor, but the docs already say as much, and it is a much narrower case. I was thinking that, since the time range might be rough anyway, users could simply widen the window to search for more records. But your point is also valid. In some cases, such as verifying the function using a small window, using outer anchors is more reasonable. Yes, outer anchors can still be used with binary search. I have changed v3 to use outer anchors, and your reproducer now gets: ``` evantest=# SELECT l.start_lsn, l.end_lsn, :'delete_lsn'::pg_lsn AS delete_lsn evantest-# FROM pg_get_wal_location_at_time(:'window_start', evantest(# interval '500 milliseconds', evantest(# :'window_end'::timestamptz - evantest(# :'window_start'::timestamptz) AS l; start_lsn | end_lsn | delete_lsn ------------+------------+------------ 0/01C50430 | 0/01C504F0 | 0/01C50490 (1 row) ``` > > Separately, reading the code, a window that contains no timestamped record, > but has some on both sides, currently ends in "could not find a valid WAL > range for the requested time window" with the detail "The matching lower boundary follows the upper boundary in WAL". That reads like a WAL ordering > problem, when the real cause is that nothing in the window is timestamped. > With outer anchors this case would just return a range. Yes. I added a tested for that. PFA v3 - addressed Surya’s review comments. Best regards, -- Chao Li (Evan) HighGo Software Co., Ltd. https://www.highgo.com/
Re: pg_walinspect: add functions to locate and list WAL by time and LSN
От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Chao,
Thanks for v3. Moving to outer anchors with the fallback to the current WAL position addresses my concern with v2, and I appreciate the new tests
covering both the empty-window case and the DELETE scenario.
v3 applies cleanly to master (f884f359f5a) and builds without warnings.
Locally, the regression tests and both TAP tests pass, and so does my earlier reproducer. The returned range now brackets the DELETE:
start_lsn | end_lsn | delete_lsn
------------+------------+------------
0/017F0220 | 0/017F02E0 | 0/017F0280
However, CFBot's macOS - Meson job fails on v3 (https://github.com/postgres/postgres-cfbot/actions/runs/37738280802/job/113183259446) in 001_timeline.pl, during the archive_mode=0 pass:
ERROR: WAL segment needed for the requested range is missing
DETAIL: Segment 4 is not present in pg_wal.
... FROM pg_get_wal_files('0/04001790', pg_current_wal_lsn())
The standby's server log from that run points to a race in the test rather than a bug in pg_get_wal_files():
06:52:52.657 received promote request
06:52:52.701 checkpoint starting: force
06:52:52.938 checkpoint complete: ... 0 WAL file(s) added, 0 removed, 2 recycled
06:52:52.972 ERROR: WAL segment needed for the requested range is missing
The checkpoint forced by the promotion recycled two WAL segments, and since segment 4, which holds start_lsn, was gone 34 ms later, it must have been
one of them. On a faster machine the query runs before that checkpoint completes, which would explain why the test passes locally.
Keeping that WAL on the standby makes the test deterministic. I confirmed this locally with a copy of the test that forces a CHECKPOINT right after
promote(): it fails every time with the same "Segment 4 is not present" error, and passes once the standby has wal_keep_size set:
$standby->init_from_backup($primary, $backup_name, has_streaming => 1);
$standby->append_conf('postgresql.conf', "wal_keep_size = '64MB'");
src/test/recovery/t/004_timeline_switch.pl uses wal_keep_size the same way.
One small question on 0001. For a point lookup at the current LSN on a segment boundary, v3 now returns the preceding segment, which makes sense
given that the next file may not exist yet. pg_walfile_name(), though, maps the same LSN to the next segment (it uses XLByteToSeg). So at that one LSN
the two functions name different files. I'm fine with the choice, since the docs explain it, but it may be worth a sentence noting the difference from
pg_walfile_name().
Regards,
Surya Poondla
Thanks for v3. Moving to outer anchors with the fallback to the current WAL position addresses my concern with v2, and I appreciate the new tests
covering both the empty-window case and the DELETE scenario.
v3 applies cleanly to master (f884f359f5a) and builds without warnings.
Locally, the regression tests and both TAP tests pass, and so does my earlier reproducer. The returned range now brackets the DELETE:
start_lsn | end_lsn | delete_lsn
------------+------------+------------
0/017F0220 | 0/017F02E0 | 0/017F0280
However, CFBot's macOS - Meson job fails on v3 (https://github.com/postgres/postgres-cfbot/actions/runs/37738280802/job/113183259446) in 001_timeline.pl, during the archive_mode=0 pass:
ERROR: WAL segment needed for the requested range is missing
DETAIL: Segment 4 is not present in pg_wal.
... FROM pg_get_wal_files('0/04001790', pg_current_wal_lsn())
The standby's server log from that run points to a race in the test rather than a bug in pg_get_wal_files():
06:52:52.657 received promote request
06:52:52.701 checkpoint starting: force
06:52:52.938 checkpoint complete: ... 0 WAL file(s) added, 0 removed, 2 recycled
06:52:52.972 ERROR: WAL segment needed for the requested range is missing
The checkpoint forced by the promotion recycled two WAL segments, and since segment 4, which holds start_lsn, was gone 34 ms later, it must have been
one of them. On a faster machine the query runs before that checkpoint completes, which would explain why the test passes locally.
Keeping that WAL on the standby makes the test deterministic. I confirmed this locally with a copy of the test that forces a CHECKPOINT right after
promote(): it fails every time with the same "Segment 4 is not present" error, and passes once the standby has wal_keep_size set:
$standby->init_from_backup($primary, $backup_name, has_streaming => 1);
$standby->append_conf('postgresql.conf', "wal_keep_size = '64MB'");
src/test/recovery/t/004_timeline_switch.pl uses wal_keep_size the same way.
One small question on 0001. For a point lookup at the current LSN on a segment boundary, v3 now returns the preceding segment, which makes sense
given that the next file may not exist yet. pg_walfile_name(), though, maps the same LSN to the next segment (it uses XLByteToSeg). So at that one LSN
the two functions name different files. I'm fine with the choice, since the docs explain it, but it may be worth a sentence noting the difference from
pg_walfile_name().
Regards,
Surya Poondla
Re: pg_walinspect: add functions to locate and list WAL by time and LSN
> On Oct 9, 2026, at 06:36, surya poondla wrote:
>
> Hi Chao,
>
> Thanks for v3. Moving to outer anchors with the fallback to the current WAL position addresses my concern with v2, and I appreciate the new tests
> covering both the empty-window case and the DELETE scenario.
>
> v3 applies cleanly to master (f884f359f5a) and builds without warnings.
> Locally, the regression tests and both TAP tests pass, and so does my earlier reproducer. The returned range now brackets the DELETE:
>
> start_lsn | end_lsn | delete_lsn
> ------------+------------+------------
> 0/017F0220 | 0/017F02E0 | 0/017F0280
>
>
> However, CFBot's macOS - Meson job fails on v3 (https://github.com/postgres/postgres-cfbot/actions/runs/37738280802/job/113183259446) in 001_timeline.pl, during the archive_mode=0 pass:
>
> ERROR: WAL segment needed for the requested range is missing
> DETAIL: Segment 4 is not present in pg_wal.
> ... FROM pg_get_wal_files('0/04001790', pg_current_wal_lsn())
>
> The standby's server log from that run points to a race in the test rather than a bug in pg_get_wal_files():
>
> 06:52:52.657 received promote request
> 06:52:52.701 checkpoint starting: force
> 06:52:52.938 checkpoint complete: ... 0 WAL file(s) added, 0 removed, 2 recycled
> 06:52:52.972 ERROR: WAL segment needed for the requested range is missing
>
> The checkpoint forced by the promotion recycled two WAL segments, and since segment 4, which holds start_lsn, was gone 34 ms later, it must have been
> one of them. On a faster machine the query runs before that checkpoint completes, which would explain why the test passes locally.
>
> Keeping that WAL on the standby makes the test deterministic. I confirmed this locally with a copy of the test that forces a CHECKPOINT right after
> promote(): it fails every time with the same "Segment 4 is not present" error, and passes once the standby has wal_keep_size set:
>
> $standby->init_from_backup($primary, $backup_name, has_streaming => 1);
> $standby->append_conf('postgresql.conf', "wal_keep_size = '64MB'");
>
> src/test/recovery/t/004_timeline_switch.pl uses wal_keep_size the same way.
Fixed by setting wal_keep_size, which prevents the required WAL file from being recycled.
>
> One small question on 0001. For a point lookup at the current LSN on a segment boundary, v3 now returns the preceding segment, which makes sense
> given that the next file may not exist yet. pg_walfile_name(), though, maps the same LSN to the next segment (it uses XLByteToSeg). So at that one LSN
> the two functions name different files. I'm fine with the choice, since the docs explain it, but it may be worth a sentence noting the difference from
> pg_walfile_name().
>
I think the two functions do different things, although their names sound similar. pg_walfile_name(lsn) performs a pure calculation that maps an LSN to a WAL file name without checking if the file exists, while pg_get_wal_files(start_lsn, end_lsn) returns a list of WAL files found on disk. We can add a sentence to the doc to clarify this difference.
PFA v4:
* 0001 - Fixed the fragile TAP test, and enhanced the doc.
* 0002 - Tiny doc formatting changes.
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
Re: pg_walinspect: add functions to locate and list WAL by time and LSN
От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Chao,
Thanks for v4. The test fix and the doc sentence look good, and CFBot is green now, including macOS.
I did a full read-through of v4, especially the boundary logic in 0002.
The binary search, the outer anchors, the extra segment scanned on each side, and the fallback to the current WAL position all look correct to
me. The tie-breaks and the neighbour scan only ever widen the range, which is the safe direction.
I have a few small comments:
1. pg_get_wal_records_info(start_lsn, end_lsn) includes the start-anchor record but not the end-anchor one.
end_lsn is the start LSN of the end-anchor record, and pg_get_wal_records_info() only returns records that end at or before
end_lsn. So if the transaction of interest committed just after the window, its COMMIT can be the end anchor, the user sees its changes but
not its commit, and might conclude it never committed. I wouldn't change end_lsn, since pointing pg_get_wal_record_info() at it to see the anchor
is useful, but a sentence in the docs would help. (This only applies when an end anchor is found, not when end_lsn falls back to the current WAL position.)
2. The docs say "Unlike the other pg_walinspect functions, this function may inspect retained WAL from the current timeline's history as well as
the current timeline." I don't think that's accurate. The existing functions read through read_local_xlog_page_no_wait(), and
XLogReadDetermineTimeline() already follows the timeline history, choosing each segment's timeline with tliOfPointInHistory(), the same
rule GetWalTimeSegments() uses. I'd drop the sentence.
3. Nit: "No retained WAL segment contains a timestamped record" is
reported with ERRCODE_INVALID_PARAMETER_VALUE, but nothing is wrong with
the arguments. ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE, which the patch
already uses for "no retained WAL segments are available", seems a better fit.
With these addressed, I think the patch is ready for committer.
Regards,
Surya Poondla
Thanks for v4. The test fix and the doc sentence look good, and CFBot is green now, including macOS.
I did a full read-through of v4, especially the boundary logic in 0002.
The binary search, the outer anchors, the extra segment scanned on each side, and the fallback to the current WAL position all look correct to
me. The tie-breaks and the neighbour scan only ever widen the range, which is the safe direction.
I have a few small comments:
1. pg_get_wal_records_info(start_lsn, end_lsn) includes the start-anchor record but not the end-anchor one.
end_lsn is the start LSN of the end-anchor record, and pg_get_wal_records_info() only returns records that end at or before
end_lsn. So if the transaction of interest committed just after the window, its COMMIT can be the end anchor, the user sees its changes but
not its commit, and might conclude it never committed. I wouldn't change end_lsn, since pointing pg_get_wal_record_info() at it to see the anchor
is useful, but a sentence in the docs would help. (This only applies when an end anchor is found, not when end_lsn falls back to the current WAL position.)
2. The docs say "Unlike the other pg_walinspect functions, this function may inspect retained WAL from the current timeline's history as well as
the current timeline." I don't think that's accurate. The existing functions read through read_local_xlog_page_no_wait(), and
XLogReadDetermineTimeline() already follows the timeline history, choosing each segment's timeline with tliOfPointInHistory(), the same
rule GetWalTimeSegments() uses. I'd drop the sentence.
3. Nit: "No retained WAL segment contains a timestamped record" is
reported with ERRCODE_INVALID_PARAMETER_VALUE, but nothing is wrong with
the arguments. ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE, which the patch
already uses for "no retained WAL segments are available", seems a better fit.
With these addressed, I think the patch is ready for committer.
Regards,
Surya Poondla
Re: pg_walinspect: add functions to locate and list WAL by time and LSN
> On Oct 10, 2026, at 07:18, surya poondla wrote: > > Hi Chao, > > Thanks for v4. The test fix and the doc sentence look good, and CFBot is green now, including macOS. Thank you very much for the follow up reviewing. > > I did a full read-through of v4, especially the boundary logic in 0002. > The binary search, the outer anchors, the extra segment scanned on each side, and the fallback to the current WAL position all look correct to > me. The tie-breaks and the neighbour scan only ever widen the range, which is the safe direction. Cool! > > I have a few small comments: > 1. pg_get_wal_records_info(start_lsn, end_lsn) includes the start-anchor record but not the end-anchor one. > end_lsn is the start LSN of the end-anchor record, and pg_get_wal_records_info() only returns records that end at or before > end_lsn. So if the transaction of interest committed just after the window, its COMMIT can be the end anchor, the user sees its changes but > not its commit, and might conclude it never committed. I wouldn't change end_lsn, since pointing pg_get_wal_record_info() at it to see the anchor > is useful, but a sentence in the docs would help. (This only applies when an end anchor is found, not when end_lsn falls back to the current WAL position.) > This is a good point. Since the requested time range is likely to be only a rough estimate, users may generally be more interested in the surrounding WAL than in the exact endpoint. But I agree that this can sometimes matter. I considered changing end_lsn to the end-anchor record's ending LSN, but then pg_get_wal_record_info(end_lsn) could no longer be used to inspect the end-anchor record directly. Therefore, I added a tip to the doc explaining this situation and how to include the end-anchor record. > 2. The docs say "Unlike the other pg_walinspect functions, this function may inspect retained WAL from the current timeline's history as well as > the current timeline." I don't think that's accurate. The existing functions read through read_local_xlog_page_no_wait(), and > XLogReadDetermineTimeline() already follows the timeline history, choosing each segment's timeline with tliOfPointInHistory(), the same > rule GetWalTimeSegments() uses. I'd drop the sentence. Agreed. > > 3. Nit: "No retained WAL segment contains a timestamped record" is > reported with ERRCODE_INVALID_PARAMETER_VALUE, but nothing is wrong with > the arguments. ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE, which the patch > already uses for "no retained WAL segments are available", seems a better fit. Agreed. > > With these addressed, I think the patch is ready for committer. > > Regards, > Surya Poondla PFA v5: 0001 unchanged; 0002 addressed the new comments. Best regards, -- Chao Li (Evan) HighGo Software Co., Ltd. https://www.highgo.com/
Re: pg_walinspect: add functions to locate and list WAL by time and LSN
От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Thank you, Chao.
v5 addresses all of my comments. The doc and errcode changes look good. The regression and TAP tests pass locally on master (f884f359f5a), CFBot is green, and pgindent reports no changes for the C files.
The changes look good for a Committer.
Regards,
Surya Poondla
v5 addresses all of my comments. The doc and errcode changes look good. The regression and TAP tests pass locally on master (f884f359f5a), CFBot is green, and pgindent reports no changes for the C files.
The changes look good for a Committer.
Regards,
Surya Poondla
Re: pg_walinspect: add functions to locate and list WAL by time and LSN
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi, On Thu, Sep 17, 2026 at 9:06 PM Chao Li wrote: > > I'd like to propose adding two new SQL functions to pg_walinspect. Thanks, and sorry for the delay. > During HOW2026 in Jinan this April, a DBA talked to me that PG lacks an easy way to locate WAL files by time. I think using the existing pg_walinspect functions, one can look up the times using the transaction commit/abort time from the description column, starting from the last checkpoint's redo LSN till the current flush LSN. Isn't this helpful? It takes a bit of time to do so, but that should be fine. > He described a scenario where somebody had done something wrong in a production database, for example accidentally deleting important data. The administrator knew that the incident had happened at around 1am the last night and wanted to confirm what had happened by analyzing WAL. Isn't one expected to set up *some* kind of auditing or delayed streaming standby or such in production if worried about such accidental deletes/drops? > The problem was that, with thousands of WAL files in pg_wal, where should he start? WAL files are archived and renamed/reused/removed, so all the thousands of files, one of which could be the interesting file containing the accidental WAL records, are not guaranteed to be available in the pg_wal dir anyway. 1000 WAL files come to around 16GB, and I'm not sure if anyone really prefers to delay checkpoints beyond that point (max_wal_size is also usually set up to trigger the checkpoint). If needed, one can use pg_waldump and some scripts to do the analysis independently of the database instance. I'm not against enhancing pg_walinspect for more use cases. However, I'm a bit worried about complicating it for this. Unless I'm missing something here, the reported issue could have been solved with a bit of SQL over the existing functions and/or with some scripting with pg_waldump over pg_wal dir or the archived WAL. -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: pg_walinspect: add functions to locate and list WAL by time and LSN
От:
Chao Li <li.evan.chao@gmail.com>
Дата:
> On Nov 18, 2026, at 01:17, Bharath Rupireddy wrote: > > Hi, > > On Thu, Sep 17, 2026 at 9:06 PM Chao Li wrote: >> >> I'd like to propose adding two new SQL functions to pg_walinspect. > > Thanks, and sorry for the delay. Thanks a lot for your feedback. > >> During HOW2026 in Jinan this April, a DBA talked to me that PG lacks an easy way to locate WAL files by time. > > I think using the existing pg_walinspect functions, one can look up > the times using the transaction commit/abort time from the description > column, starting from the last checkpoint's redo LSN till the current > flush LSN. Isn't this helpful? It takes a bit of time to do so, but > that should be fine. I'm afraid that's not easy. As I implemented in the patch, I even chose to use a binary search to find the start and end LSN boundaries for a time range. I don't think this can be done easily with just a few SQL statements, especially for ordinary DBAs. I've heard from many DBAs who have requested such a function. Surya also agreed that this is a real use case. > >> He described a scenario where somebody had done something wrong in a production database, for example accidentally deleting important data. The administrator knew that the incident had happened at around 1am the last night and wanted to confirm what had happened by analyzing WAL. > > Isn't one expected to set up *some* kind of auditing or delayed > streaming standby or such in production if worried about such > accidental deletes/drops? We cannot imagine all users' operational models. I started talking to DBAs last year. My main takeaway is that real-world use cases are usually far more complicated than what I can imagine as a hacker writing PostgreSQL code. I didn't come up with this feature myself; some DBAs requested it. > >> The problem was that, with thousands of WAL files in pg_wal, where should he start? > > WAL files are archived and renamed/reused/removed, so all the > thousands of files, one of which could be the interesting file > containing the accidental WAL records, are not guaranteed to be > available in the pg_wal dir anyway. 1000 WAL files come to around > 16GB, and I'm not sure if anyone really prefers to delay checkpoints > beyond that point (max_wal_size is also usually set up to trigger the > checkpoint). If needed, one can use pg_waldump and some scripts to do > the analysis independently of the database instance. I guess users would be more likely to set wal_keep_size to a large value in order to retain more WAL files. Yes, users can write scripts to do whatever kind of analysis. But here, users want a simple, native PG method. This patch is trying to address a user requirement and make DBAs' lives a bit easier. Also, this patch doesn't touch the core, it just adds two new functions to the pg_walinspect extension. > > I'm not against enhancing pg_walinspect for more use cases. However, > I'm a bit worried about complicating it for this. Unless I'm missing > something here, the reported issue could have been solved with a bit > of SQL over the existing functions and/or with some scripting with > pg_waldump over pg_wal dir or the archived WAL. > I don't feel this patch adds significant complexity to pg_walinspect. This feature doesn't change the existing logic of pg_walinspect, it only adds two new functions. And as explained above, what the new functions do is not as easy to achieve with just a bit of SQL. Whenever possible, we should try to improve the user experience. Best regards, -- Chao Li (Evan) HighGo Software Co., Ltd. https://www.highgo.com/