UNDO with constant time recovery (CTR)

Поиск
Список
Период
Сортировка
Искать

UNDO with constant time recovery (CTR)

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
Hello hackers,

Postgres from the start has not implemented the concept of UNDO WAL log
records depending only on REDO during recovery to return to a consistent
state.  This was an intentional omission, not an oversight and a good
one that has stood the test of time.

Famously the ZHeap project implemented UNDO as a stepping stone to a new
table AM by that name to replace HEAP.  The idea was to avoid some of
the pitfalls of HEAP's MVCC design, primarily "bloat" in tables and
indexes which requires VACUUM to eliminate.  Another attempt at UNDO was
in the Zedstore table AM, a hybrid row/column system with UNDO.  Both
these projects showed great promise, but neither delivered.

So UNDO has a history here, and it is important to recognize that up
front.  I'd like to acknowledge that this work builds directly on a
decade of prior work by many people.  So much so that I'm sure I've left
someone or something off this list, apologies in advance and feel free
to reply with more links referencing more of the history of UNDO in
Postgres.

   Undo logs, Thomas Munro
     https://postgr.es/m/CAEepm=2EqROYJ_xYz4v5kfr4b0qw_Lq_6Pe8RTEC8rx3upWsSQ@mail.gmail.com
   Undo worker and transaction rollback, Dilip Kumar
     https://postgr.es/m/CAFiTN-sYQ8r8ANjWFYkXVfNxgXyLRfvbX9Ee4SxO9ns-OBBgVA@mail.gmail.com
   POC: Cleaning up orphaned files using undo logs, Thomas Munro, later Antonin Houska
     https://postgr.es/m/CAEepm=0ULqYgM2aFeOnrx6YrtBg3xUdxALoyCG+XpssKqmezug@mail.gmail.com
     https://postgr.es/m/20190203100944.qwcf2ctclf75so7c@alap3.anarazel.de
     https://postgr.es/m/45455.1637848942@antos
   zheap: a new storage format for PostgreSQL, Amit Kapila et al.
     https://github.com/EnterpriseDB/zheap
     https://postgr.es/m/CAA4eK1+YtM5vxzSM2NZm+pC37MCwyvtkmJrO_yRBQeZDp9Wa2w@mail.gmail.com
   Logical decoding for operations on zheap tables, Amit Kapila
     https://postgr.es/m/CAA4eK1JeGWBKR6nRMMUXQhSMsEQHUPHm3XVLHfUrDvrceN+WFg@mail.gmail.com
   Zedstore - compressed in-core columnar storage, Ashwin Agrawal
     https://postgr.es/m/CALfoeiuF-m5jg51mJUPm5GN8u396o5sA2AF5N97vTRAEDYac7w@mail.gmail.com
   undo: zedstore vs. zheap, Robert Haas
     https://postgr.es/m/CA+TgmoYeTeQSmALox0PmSm5Gh03oe=UNjhmL+K+btofY_U2jFQ@mail.gmail.com
   Orphaned relation files after crash recovery, Masahiko Sawada
     https://postgr.es/m/CA+fd4k7KHw0E5t9_4LFmsiFYL7SQrtwK312TQQ8q0gUDmy3jkw@mail.gmail.com

I started working on this by first resurrecting the ZHeap UNDO code,
then resurrecting Zedstore.  This work dovetails my other major thread
about "Tepid" which builds on PHOT and the heap-only tuple (HOT)
optimizations.

All these authors and more deserve credit for their hard work, thank
you.  In the case of ZHeap and Zedstore the ultimate goal was a new table
AM.  I'm not going to boil that ocean up front, here is where I'm going
to diverge from those past projects.

* there is no change to HEAP in this patch set
* there are some changes to nbtree and hash, but they are additive and
   gated by a new index_undo reloption; they consume 0001 but touch no
   existing index behavior when a transaction commits, foundational for
   review only designed to trigger discussion at this point
* there is a new table AM in this patch set called FLUX, but it is a
  prototype/demo/not finished and not intended to replace HEAP

There is nothing wrong with the way Postgres does WAL logging or
recovery today.  And the HEAP table AM is a thing of beauty, despite its
appearances, that has carried production load for the lifetime of
Postgres at a scale never anticipated by anyone involved. The process of
vacuuming tables has dramatically improved over the years and continues
to be an area of active development addressing the bloat issue head on
with continued refinement of the autovacuum process, the
concurrency/efficiency of vacuuming, and now we have REPACK.  So why
resurrect UNDO?

I feel that the flexibility of Postgres is one of its core strengths.
I'd like to see more innovation, different shapes of table and index AMs
supported in core and as extensions over time.  I'd like to offer users
of Postgres different operational trade-offs, in particular one that
shifts the burden of "bloat" from table/index to the WAL, which is what
UNDO can do and ZHeap targeted but never delivered.  That's a longer
term goal.  In my opinion, there exist a number of use cases for a
system that provides UNDO.  The ability to recover a stateful change to
a consistent state is valuable in a database.

One good example is "orphaned files" or other changes to the state of
filesystem objects at runtime [1].  It's my view that these stateful
changes should behave as anything else that is transactional, during
recovery they in-flight or aborted changes should be undone so as
provide a consistent state at startup.  So, rather than build a new
table AM as the first justification for UNDO I've built "transational
filesystem operations" (FILEOPS for short) and changed all our calls
from things like mkdir() to FileOpsMkdir().  Here's the list of
supported operations:

   FileOpsCreate(path, flags, mode, register_delete)
   FileOpsDelete(path, at_commit)
   FileOpsRename(oldpath, newpath)
   FileOpsWrite(path, offset, data, len)
   FileOpsTruncate(path, length)
   FileOpsChmod(path, mode)
   FileOpsChown(path, uid, gid)
   FileOpsMkdir(path, mode)
   FileOpsRmdir(path, at_commit)
   FileOpsRmdirRecursive(path, at_commit)
   FileOpsRmtree(path, at_commit)
   FileOpsSymlink(target, linkpath)
   FileOpsLink(oldpath, newpath)
   FileOpsSetXattr(path, name, value, len)
   FileOpsRemoveXattr(path, name)

If a transaction is in flight and creates a new file and then crashes to
me it makes sense that after recovery that new file is gone and the
system is consistent again.  I felt this would be a good, small but
important, first step into the use of UNDO in a few places in Postgres.

This isn't a new idea, I used to work for Sleepycat and write code
improving Berkeley DB years (decades!) ago and it includes the ability
to log filesystem changes in the WAL and then recover them to well known
state, so why not Postgres?

Another idea might be new work on LOB (or BLOB/CLOB) type that can use
UNDO to manage state stored on the filesystem or elsewhere.

The attached set of patches has a few that are very large, UNDO is split
across 0001 (cluster-wide), 0004 (per-backend), and 0005 (ATM/sLog), it
is not a small.  Obviously if FILEOPS was my only target for this major
addition to core the idea should be rejected and we should get back to
work on [1] or something similar.  I think adding UNDO as a generic
subsystem will bring new innovations to Postgres that are impossible or
too complex as the system stands today.  But I'm only once voice here in
this community, so before I invest more time in the prototype table AMs
based on UNDO I need to see if this is something we all agree should be
integrated into core.

The generic UNDO system in the attached patches provides two modes,
logging into the common WAL log along with all the REDO, etc. records is
one way and it's how FILEOPS is implemented.  But ZHeap had a different
idea, a WAL log per-backend, and my two prototype table AMs use that
model for UNDO. I'll not go into the differences or reasoning here, I've
attached two wiki page drafts and in the src/backend/access/undo/README
there is a ton of detail so please read that before responding with
thoughts.

The v1 patches are:

    0001  UNDO: add the cluster-wide UNDO engine
    0002  FILEOPS: transactional filesystem operations with UNDO in the common WAL
    0003  Route transactional filesystem operations through FILEOPS
    0004  UNDO: add the per-backend UNDO logs
    0005  UNDO: add the ATM, sLog, and logical revert worker
    0006  INDEX: nbtree UNDO for rollback without VACUUM
    0007  INDEX: hash UNDO for rollback without VACUUM
    0008  INDEX: nbtree delete-marking for in-place indexed-column UPDATE

0001 - is the engine: undo records written into the normal WAL stream, a
resource-manager dispatch so any access method can register an rm_undo
callback keyed by its own record id, transaction integration, and
application of an aborted transaction's undo chain inline at abort and
at the end of recovery. Nothing in 0001 knows about HEAP, indexes, or
any table AM; the core stays format-agnostic and interprets a record
only through the owning rmgr's callback.

0002 and 0003 are the first consumer and a large part of why I think
this foundation is worth reviewing now: transactional filesystem
operations. CREATE DATABASE, tablespace directory creation, and the copy
paths currently leave orphaned files behind when a transaction or the
server dies at the wrong moment. FILEOPS runs constructive operations
(create, mkdir, chmod, symlink) immediately and registers an abort-time
undo action to remove them, and defers destructive operations (rename,
delete, rmdir, rmtree) to commit. On abort or crash the undo chain
removes exactly what the transaction created; on commit the deferred
removals run. It is carried correctly through 2PC. This is the problem
Thomas started on in the orphaned-files POC thread [1], approached
through the same undo machinery rather than a bespoke pending-ops list.

0004 and 0005 are the remaining pieces the table access methods I'm
working toward need, included here so the engine is complete rather than
a stub: per-backend undo logs (buffered, discardable undo segment
storage owned per top-level transaction), and constant-time rollback via
an aborted-transaction map plus a background worker that applies undo
chains asynchronously. Unlike 0001, these two have no in-tree consumer
in this thread; the FLUX and RECNO table AMs that use them come later.
I've kept them here so the foundation can be reviewed as a whole, but if
the list would rather I hold 0004 and 0005 until their first consumer,
say so and I'll drop them from this thread.

0006, 0007 and 0008 are the second consumer, and they exercise the
engine harder. 0006 and 0007 make an aborted transaction leave no index
work for VACUUM: each leaf entry a transaction inserts writes one small
record into the cluster-wide UNDO stream (heap TID, length, and a digest
of the key, not the tuple itself), and on abort the chain walk marks
just those entries LP_DEAD, wherever a later insert or a page split
moved them. It is a heap reloption, index_undo, on by default. 0008 adds
nbtree delete-marking, the piece a stable-TID in-place-UPDATE table AM
needs to keep a row's TID when an indexed column changes. Heap itself
writes no UNDO in any of this and is unchanged.

0009 is the FLUX table AM, a prototype that I've been tinkering with
during development of UNDO and included not as a replacement for HEAP.

The per-backend engine in 0004 derives from the ZHeap UNDO work; those
authors are credited in that patch's commit message. Where this design
differs from the 2019 patch set it is mostly in the directions Robert's
zedstore-vs-zheap notes pointed: UNDO chained per tuple, not per block;
a per-record apply callback, not per-page; the top-level xid used for
subtransactions; and a freshly inserted tuple needs no undo record for
visibility. Tuple locking is still the open question it was in that
thread; I use a heavyweight tuple lock for now and would welcome
opinions.

I know this is a large area with a long history. I've tried to make the
entry point small: 0001 plus FILEOPS (0002, 0003) is a complete,
testable feature set that stands on its own, and I'd value review of
that boundary first.

Design write-ups kept current with the code in
src/backend/access/undo/README and wiki pages.

For the record LLMs did participate in this process, but this was not a
"vibe-coded UNDO system".  You might find an LLM-ism or two somewhere, I
tried to audit all the code in my last review before sending but I'm not
perfect and neither are they.  I've worked on it extensively and I've
used LLMs to provide feedback, polish, find corner cases, find missing
but required features, do security reviews, etc.  This has been in the
works for over a year, I hope you're interested enough to give it a look
and let me know your thoughts.  The only part of this email an LLM
produced was the per-patch descriptions above, the rest is me.

Also, I realize that this kind of change takes a lot of time to gain
traction and adoption into core, if at all.  I'm ready for that, sure
we're working on v20 now and v19 is inching out the door maybe this
merges into v25 or maybe it gets shelved along the way for good reason.
Who knows, but I do know that it's worth the effort to advocate and to
have a durable record for others interested in it even if it doesn't get
merged in this time.  I look forward to seeing what happens.  :)

best.

-greg

PS: I have two UNDO-based table AMs that under development, FLUX and
RECNO, but neither is ready for production use or intended as a
replacement for HEAP.
https://github.com/gburd/postgres/tree/undo/src/backend/access/flux
https://github.com/gburd/postgres/tree/undo/src/backend/access/recno

[1] https://postgr.es/m/Hjyy_5of-vqSTyKUyYgK8WjlA49tMG-GmitHDPI02SVcqz1ckxfTwpPo4R92neovTfeaQAlxWzOBVyx7bgKA07j1s9V3BeOsHYTuwTg0468%3D%40burd.me

Re: UNDO with constant time recovery (CTR)

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
Hello.

I've rebased this onto 425daf545d9 v2 attached and created https://commitfest.postgresql.org/patch/7389

best.

-greg

Re: UNDO with constant time recovery (CTR)

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Hi Gregm

Thank you for all the work on this. I like the approach of starting
with FILEOPS and not with a new table AM. I tried 0001 to 0003 from
v2 and have a few notes. Please correct me if I got something wrong.

1. Most FILEOPS tests seem to need 0005 to run. 059 and 061 set
logical_revert_naptime, which 0005 adds. 060 and 072 are skipped
because test_fileops is only added to the build in 0005.

2. A crash in the middle of CREATE DATABASE still leaves the
directory for me. With wal_log I get

  WARNING:  FILEOPS UNDO MKDIR: could not rmdir "base/77777":
  Directory not empty

With file_copy I do not see any undo run.

3. A plain file system error can now crash the server. For example,
when the tablespace directory is owned by root:

  CREATE TABLESPACE t LOCATION '/Users/Shared';

On master I get

  ERROR:  could not set permissions on directory "/Users/Shared":
  Operation not permitted

With the patch I get

  PANIC:  could not chmod file "/Users/Shared": Operation not
  permitted

and all sessions are dropped while the server does crash recovery.
I think it is because FileOpsChmod() calls chmod() inside the
critical section, so the ERROR turns into a PANIC. The other FileOps
functions look the same. Is that intended?

You asked about 0004 and 0005. I think it is fine to hold them for
now.

Thanks,
Shihao

Re: UNDO with constant time recovery (CTR)

От:
Matthias van de Meent <boekewurm+postgres@gmail.com>
Дата:
On Tue, 29 Sept 2026, 00:29 Greg Burd,  wrote:
>
> Hello hackers,
>

Hi Greg,

A few things popped out in this thread, so here's a few comments.

[...]

> All these authors and more deserve credit for their hard work, thank
> you.  In the case of ZHeap and Zedstore the ultimate goal was a new table
> AM.  I'm not going to boil that ocean up front, here is where I'm going
> to diverge from those past projects.

I'd prefer if you didn't boil any oceans in the process of making
contributions.  Not up front is a good start, but please don't do that
later on, either.

[...]

> If a transaction is in flight and creates a new file and then crashes to
> me it makes sense that after recovery that new file is gone and the
> system is consistent again.

That very much depends on the type of file created. E.g. WAL files,
SLRU files, and new segments of existing relations should not be
removed just because they were created by a transaction that crashed
or rolled back -- other backends may have have written to those files.

Also note that we may want to have UNDO outside transactional
boundaries:  after all, not all DDL is transactional, and I think
there's some gain to be had for e.g. REINDEX CONCURRENTLY; it allows
us to truncate the !indisready index files it leaves behind after a
crash, reducing disk bloat in those cases.


Side note:  I'd prefer if this change does _not_ mean that unlogged
relations get to WAL-log proportional to data operations.  Undo
logging can be useful, but should not be predicated on WAL if a
tableAM requires UNDO.

[...]

> Also, I realize that this kind of change takes a lot of time to gain
> traction and adoption into core, if at all.  I'm ready for that, sure
> we're working on v20 now and v19 is inching out the door maybe this
> merges into v25 or maybe it gets shelved along the way for good reason.
> Who knows, but I do know that it's worth the effort to advocate and to
> have a durable record for others interested in it even if it doesn't get
> merged in this time.  I look forward to seeing what happens.  :)

The title indicates constant-time recovery, but I don't see anything
in this thread that supports this claim.  Could you expand on the
mechanisms you're using to guarantee this?

I also don't see how your claimed constant-time rollback can work,
given that the size of a transaction's modified working set is bounded
only by time and the space available to store the database, and that
undoing changes in files can't really be done faster than the
bandwidth of your CPU.  Undoing a set of transaction operations
therefore can't really be constant-time unless you're limiting the
number of undo-able transaction operations, and a limited transaction
size is not really something current users have to consider (and thus,
don't expect).


Kind regards,

Matthias van de Meent
Databricks (https://www.databricks.com)


Re: UNDO with constant time recovery (CTR)

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Hi Matthias,

> The title indicates constant-time recovery, but I don't see anything
> in this thread that supports this claim.  Could you expand on the
> mechanisms you're using to guarantee this?

I built the v2 series and measured this, since it is checkable. Two
things, both on v2 (test_fileops is the knob: each call records one undo
record; the heap AM does not opt into UNDO, so ordinary DML generates
none).

First, a scoping note. The O(1) claim is stated for the sparse case
(README.undo:105): "a handful of filesystem or structural operations per
transaction ... O(1) from the client's perspective." It is not a claim
that total undo work is constant -- the design defers that work, it does
not remove it. So for the two client-visible costs below, the question is
really whether they stay flat as the undo chain grows past "a handful".

1) ROLLBACK latency vs undo-chain length N (one txn, N chmods, timing the
ROLLBACK only, median of 5, self-checked that the chain was actually
applied). ROLLBACK ms by undo_instant_abort_threshold regime:

- default (65536): N=200 is 0.37, N=1000 is 1.41, N=8000 is 9.74,
  N=32000 is 37.6
- forced inline (large threshold): N=200 is 0.37, N=1000 is 1.81,
  N=8000 is 9.43, N=32000 is 70.5
- forced deferred (threshold=1): N=200 is 0.37, N=1000 is 2.49,
  N=8000 is 9.93, N=32000 is 39.1

It is linear in N in all three regimes (~1.2 us/record). Forcing the
deferred path does not make the client return in O(1): the chain is still
written and XLogFlush'd before ROLLBACK returns; deferral only moves the
physical reversal to the revert worker.

2) Crash recovery of an in-flight transaction. A backend builds N chmods
in an open txn, then the cluster is immediate-stopped. On restart the undo
phase is synchronous and the server log shows it finishing before the
cluster opens:

  starting undo phase for incomplete transactions
  UNDO recovery complete: 1 transactions rolled back, 128000 records applied
  undo phase complete
  database system is ready to accept connections (after the undo phase)

Undo phase duration, median of 2, records_applied == N every run:
N=2000 is 1.5 ms; N=32000 is 17.5 ms; N=128000 is 72.0 ms. The undo
phase is linear in N -- consistent with README.undo:119-127 (loser-txn
undo runs in the recovery pass), but it is the synchronous
undo-before-open that "constant time recovery" reads as avoiding.

None of this contradicts the mechanism -- deferring the undo of already
resolved aborts to a background worker is real and works. It is the title
and the headline O(1) that a reader takes literally. It might be worth
scoping both to the sparse case the README already assumes, or saying in
the docs that an in-flight transaction's undo is still applied at recovery
in O(chain length).

Attached are the three measurement scripts, the raw result tables, and
the recovery-log excerpt, so the numbers above can be reproduced:
ctr_rollback_latency.sh and ctr_knee.sh (test 1), ctr_recovery_time.sh
(test 2), the two .tsv outputs, and recovery_log_evidence.txt.

- Manu

Re: UNDO with constant time recovery (CTR)

От:
Greg Burd <greg@burd.me>
Дата:

> On Oct 4, 2026, at 12:11 AM, shihao zhong  wrote:
> 
> Hi Gregm

Hello Shihao! Thanks for taking a look.

> Thank you for all the work on this. I like the approach of starting
> with FILEOPS and not with a new table AM. I tried 0001 to 0003 from
> v2 and have a few notes. Please correct me if I got something wrong.

You didn't, I did.

> 1. Most FILEOPS tests seem to need 0005 to run. 059 and 061 set
> logical_revert_naptime, which 0005 adds. 060 and 072 are skipped
> because test_fileops is only added to the build in 0005.

Yes, this was an oversight.  I'm rebasing and reorganizing the
series now.

> 2. A crash in the middle of CREATE DATABASE still leaves the
> directory for me. With wal_log I get
> 
>   WARNING:  FILEOPS UNDO MKDIR: could not rmdir "base/77777":
>   Directory not empty
> 
> With file_copy I do not see any undo run.

Good catch, and this should have been in my set of tests.  I'll
add more and correct this.

> 3. A plain file system error can now crash the server. For example,
> when the tablespace directory is owned by root:
> 
>   CREATE TABLESPACE t LOCATION '/Users/Shared';
> 
> On master I get
> 
>   ERROR:  could not set permissions on directory "/Users/Shared":
>   Operation not permitted
> 
> With the patch I get
> 
>   PANIC:  could not chmod file "/Users/Shared": Operation not
>   permitted
> 
> and all sessions are dropped while the server does crash recovery.
> I think it is because FileOpsChmod() calls chmod() inside the
> critical section, so the ERROR turns into a PANIC. The other FileOps
> functions look the same. Is that intended?

Nope, just a gross oversight on my part.  Mostly corrected in my tree
this past week.  I'd hoped to have something to attach today but I'm
not quite there yet.

> You asked about 0004 and 0005. I think it is fine to hold them for
> now.
> 
> Thanks,
> Shihao

best.

-greg




Re: UNDO with constant time recovery (CTR)

От:
Greg Burd <greg@burd.me>
Дата:

> On Oct 5, 2026, at 6:59 AM, Matthias van de Meent  wrote:
> 
> On Tue, 29 Sept 2026, 00:29 Greg Burd,  wrote:
>> 
>> Hello hackers,
>> 
> 
> Hi Greg,

Hello Matthias, thanks for taking the time to review.

> A few things popped out in this thread, so here's a few comments.
> 
> [...]
> 
>> All these authors and more deserve credit for their hard work, thank
>> you.  In the case of ZHeap and Zedstore the ultimate goal was a new table
>> AM.  I'm not going to boil that ocean up front, here is where I'm going
>> to diverge from those past projects.
> 
> I'd prefer if you didn't boil any oceans in the process of making
> contributions.  Not up front is a good start, but please don't do that
> later on, either.

Ha!  Yeah, oceans are not to be boiled.  Noted.  But really what I was
saying is that although I'd included FLUX the intent of this series was
to focus on UNDO and FILEOPS and keep HEAP out of it.  Changes to index
AMs are essentially no-ops in preparation for a future where a table AM
based on UNDO could exist, so arguably they should wait for later too.

> [...]
> 
>> If a transaction is in flight and creates a new file and then crashes to
>> me it makes sense that after recovery that new file is gone and the
>> system is consistent again.
> 
> That very much depends on the type of file created. E.g. WAL files,
> SLRU files, and new segments of existing relations should not be
> removed just because they were created by a transaction that crashed
> or rolled back -- other backends may have have written to those files.

Yes, there are exceptions and I should list them.  WAL-logging an undo
record for a WAL log change is nuts, never going to work.

> Also note that we may want to have UNDO outside transactional
> boundaries:  after all, not all DDL is transactional, and I think
> there's some gain to be had for e.g. REINDEX CONCURRENTLY; it allows
> us to truncate the !indisready index files it leaves behind after a
> crash, reducing disk bloat in those cases.

Hmmm... I'll have to wrap my head around this one.  UNDO outside of
a transaction isn't something I'd sign up for, why not just wrap
these changes in transactions?  I get the DDL issue, the reindex
one sounds like a good idea.  I'll dig a bit, thanks for opening the
door on this.

> Side note:  I'd prefer if this change does _not_ mean that unlogged
> relations get to WAL-log proportional to data operations.  Undo
> logging can be useful, but should not be predicated on WAL if a
> tableAM requires UNDO.

Good point, I'll need to recheck that I indeed disable UNDO when
the relation is unlogged...

> [...]
> 
>> Also, I realize that this kind of change takes a lot of time to gain
>> traction and adoption into core, if at all.  I'm ready for that, sure
>> we're working on v20 now and v19 is inching out the door maybe this
>> merges into v25 or maybe it gets shelved along the way for good reason.
>> Who knows, but I do know that it's worth the effort to advocate and to
>> have a durable record for others interested in it even if it doesn't get
>> merged in this time.  I look forward to seeing what happens.  :)
> 
> The title indicates constant-time recovery, but I don't see anything
> in this thread that supports this claim.  Could you expand on the
> mechanisms you're using to guarantee this?

Yes, the target is [1] and possibly [2].  The technique boils down to
keeping an "aborted transaction map" (ATM) that you can build during
the recovery process which prevents the need for replaying the UNDO
records at recovery time to restore physical page information and
leaves that for a background worker.

> I also don't see how your claimed constant-time rollback can work,
> given that the size of a transaction's modified working set is bounded
> only by time and the space available to store the database, and that
> undoing changes in files can't really be done faster than the
> bandwidth of your CPU.  Undoing a set of transaction operations
> therefore can't really be constant-time unless you're limiting the
> number of undo-able transaction operations, and a limited transaction
> size is not really something current users have to consider (and thus,
> don't expect).

Take a look at the papers, I'll fix up the code and docs and wiki.
I'll check back with you on the next patch update and see if I
managed to clear this concept up or not. :)

> Kind regards,
> 
> Matthias van de Meent
> Databricks (https://www.databricks.com)

best.

-greg

[1] https://www.microsoft.com/en-us/research/wp-content/uploads/2019/06/p700-antonopoulos.pdf
[2] https://www.vldb.org/pvldb/vol19/p3916-gandikota.pdf





Re: UNDO with constant time recovery (CTR)

От:
Greg Burd <greg@burd.me>
Дата:


> On Oct 5, 2026, at 2:41 PM, Manu  wrote:
> 
> Hi Matthias,
> 
>> The title indicates constant-time recovery, but I don't see anything
>> in this thread that supports this claim.  Could you expand on the
>> mechanisms you're using to guarantee this?
> 
> I built the v2 series and measured this, since it is checkable. Two
> things, both on v2 (test_fileops is the knob: each call records one undo
> record; the heap AM does not opt into UNDO, so ordinary DML generates
> none).
> 
> First, a scoping note. The O(1) claim is stated for the sparse case
> (README.undo:105): "a handful of filesystem or structural operations per
> transaction ... O(1) from the client's perspective." It is not a claim
> that total undo work is constant -- the design defers that work, it does
> not remove it. So for the two client-visible costs below, the question is
> really whether they stay flat as the undo chain grows past "a handful".
> 
> 1) ROLLBACK latency vs undo-chain length N (one txn, N chmods, timing the
> ROLLBACK only, median of 5, self-checked that the chain was actually
> applied). ROLLBACK ms by undo_instant_abort_threshold regime:
> 
> - default (65536): N=200 is 0.37, N=1000 is 1.41, N=8000 is 9.74,
>  N=32000 is 37.6
> - forced inline (large threshold): N=200 is 0.37, N=1000 is 1.81,
>  N=8000 is 9.43, N=32000 is 70.5
> - forced deferred (threshold=1): N=200 is 0.37, N=1000 is 2.49,
>  N=8000 is 9.93, N=32000 is 39.1
> 
> It is linear in N in all three regimes (~1.2 us/record). Forcing the
> deferred path does not make the client return in O(1): the chain is still
> written and XLogFlush'd before ROLLBACK returns; deferral only moves the
> physical reversal to the revert worker.
> 
> 2) Crash recovery of an in-flight transaction. A backend builds N chmods
> in an open txn, then the cluster is immediate-stopped. On restart the undo
> phase is synchronous and the server log shows it finishing before the
> cluster opens:
> 
>  starting undo phase for incomplete transactions
>  UNDO recovery complete: 1 transactions rolled back, 128000 records applied
>  undo phase complete
>  database system is ready to accept connections (after the undo phase)
> 
> Undo phase duration, median of 2, records_applied == N every run:
> N=2000 is 1.5 ms; N=32000 is 17.5 ms; N=128000 is 72.0 ms. The undo
> phase is linear in N -- consistent with README.undo:119-127 (loser-txn
> undo runs in the recovery pass), but it is the synchronous
> undo-before-open that "constant time recovery" reads as avoiding.
> 
> None of this contradicts the mechanism -- deferring the undo of already
> resolved aborts to a background worker is real and works. It is the title
> and the headline O(1) that a reader takes literally. It might be worth
> scoping both to the sparse case the README already assumes, or saying in
> the docs that an in-flight transaction's undo is still applied at recovery
> in O(chain length).

Hey Manu,

Thank you for digging into this and doing some work to measure.  I blame
myself for being overly excited and essentially including click-bait
verbiage like "CTR" from the papers I cited to Matthias in the last reply
in the subject for this thread.

I'll do better next time.  I'll read your scripts and when I update my
patch (soon I hope) I'll include some timing of my own and then restate
or refute the claim, fair?

> Attached are the three measurement scripts, the raw result tables, and
> the recovery-log excerpt, so the numbers above can be reproduced:
> ctr_rollback_latency.sh and ctr_knee.sh (test 1), ctr_recovery_time.sh
> (test 2), the two .tsv outputs, and recovery_log_evidence.txt.
> 
> - Manu
> 

best.

-greg




Re: UNDO with constant time recovery (CTR)

От:
Matthias van de Meent <boekewurm+postgres@gmail.com>
Дата:
On Mon, 5 Oct 2026 at 21:49, Greg Burd  wrote:
>
>
> > On Oct 5, 2026, at 6:59 AM, Matthias van de Meent  wrote:
> >
> > On Tue, 29 Sept 2026, 00:29 Greg Burd,  wrote:
> >>
> >> Hello hackers,
> >>
> >
> > Hi Greg,
>
> Hello Matthias, thanks for taking the time to review.
>
> > A few things popped out in this thread, so here's a few comments.
> >
> > [...]
> >
> >> All these authors and more deserve credit for their hard work, thank
> >> you.  In the case of ZHeap and Zedstore the ultimate goal was a new table
> >> AM.  I'm not going to boil that ocean up front, here is where I'm going
> >> to diverge from those past projects.
> >
> > I'd prefer if you didn't boil any oceans in the process of making
> > contributions.  Not up front is a good start, but please don't do that
> > later on, either.
>
> Ha!  Yeah, oceans are not to be boiled.  Noted.  But really what I was
> saying is that although I'd included FLUX the intent of this series was
> to focus on UNDO and FILEOPS and keep HEAP out of it.  Changes to index
> AMs are essentially no-ops in preparation for a future where a table AM
> based on UNDO could exist, so arguably they should wait for later too.
>
> > [...]
> >
> >> If a transaction is in flight and creates a new file and then crashes to
> >> me it makes sense that after recovery that new file is gone and the
> >> system is consistent again.
> >
> > That very much depends on the type of file created. E.g. WAL files,
> > SLRU files, and new segments of existing relations should not be
> > removed just because they were created by a transaction that crashed
> > or rolled back -- other backends may have have written to those files.
>
> Yes, there are exceptions and I should list them.  WAL-logging an undo
> record for a WAL log change is nuts, never going to work.
>
> > Also note that we may want to have UNDO outside transactional
> > boundaries:  after all, not all DDL is transactional, and I think
> > there's some gain to be had for e.g. REINDEX CONCURRENTLY; it allows
> > us to truncate the !indisready index files it leaves behind after a
> > crash, reducing disk bloat in those cases.
>
> Hmmm... I'll have to wrap my head around this one.  UNDO outside of
> a transaction isn't something I'd sign up for, why not just wrap
> these changes in transactions?  I get the DDL issue, the reindex
> one sounds like a good idea.  I'll dig a bit, thanks for opening the
> door on this.
>
> > Side note:  I'd prefer if this change does _not_ mean that unlogged
> > relations get to WAL-log proportional to data operations.  Undo
> > logging can be useful, but should not be predicated on WAL if a
> > tableAM requires UNDO.
>
> Good point, I'll need to recheck that I indeed disable UNDO when
> the relation is unlogged...
>
> > [...]
> >
> >> Also, I realize that this kind of change takes a lot of time to gain
> >> traction and adoption into core, if at all.  I'm ready for that, sure
> >> we're working on v20 now and v19 is inching out the door maybe this
> >> merges into v25 or maybe it gets shelved along the way for good reason.
> >> Who knows, but I do know that it's worth the effort to advocate and to
> >> have a durable record for others interested in it even if it doesn't get
> >> merged in this time.  I look forward to seeing what happens.  :)
> >
> > The title indicates constant-time recovery, but I don't see anything
> > in this thread that supports this claim.  Could you expand on the
> > mechanisms you're using to guarantee this?
>
> Yes, the target is [1] and possibly [2].  The technique boils down to
> keeping an "aborted transaction map" (ATM) that you can build during
> the recovery process which prevents the need for replaying the UNDO
> records at recovery time to restore physical page information and
> leaves that for a background worker.
>
> > I also don't see how your claimed constant-time rollback can work,
> > given that the size of a transaction's modified working set is bounded
> > only by time and the space available to store the database, and that
> > undoing changes in files can't really be done faster than the
> > bandwidth of your CPU.  Undoing a set of transaction operations
> > therefore can't really be constant-time unless you're limiting the
> > number of undo-able transaction operations, and a limited transaction
> > size is not really something current users have to consider (and thus,
> > don't expect).
>
> Take a look at the papers, I'll fix up the code and docs and wiki.
> I'll check back with you on the next patch update and see if I
> managed to clear this concept up or not. :)

So, IIUC, the "CTR" here practically means:

    We use a small checkpoint interval for WAL-logged MVCC-versioned
REDO-able operations that don't need an online UNDO phase (this is how
PG works), and store rare UNDO operations in a side stream.
    Then we claim that the checkpoint REDO window is time-bounded
(which is true, but with checkpoint distance -dependent bounds), and
also claim that the side stream of UNDO operations is also bounded
(without showing a proof on this).

I'll have to quote Dodgeball on that: "It's a bold strategy, Cotton.
Let's see if it pays off for him."

And, indeed, the paper's metrics show that "constant time recovery"
still means "60 seconds of recovery at p99; 180 seconds recovery at
p99.99", which is a much larger difference than one should expect from
something that claims to be constant time.

Aside: The paper's claimed recovery time also explicitly does not
cover the time spent in their equivalent of an autovacuum worker,
which is tasked with running MVCC cleanup tasks for transactions that
are in their final state and created dead MVCC version in the table.
This is OK in principle, but its existence does seem like a critical
conflict for buidling tableAMs relying on this paper whilst claiming
that "it does not need vacuum".  Because this paper seems to heavily
depend on a background task that does VACUUM's job of cleaning up old
MVCC versions to avoid pushing operations onto the UNDO work queue.


Kind regards,

Matthias van de Meent
Databricks (https://www.databricks.com)


Re: UNDO with constant time recovery (CTR)

От:
Greg Burd <greg@burd.me>
Дата:


On Monday, October 5th, 2026 at 5:23 PM, Matthias van de Meent  wrote:

> On Mon, 5 Oct 2026 at 21:49, Greg Burd  wrote:
> >
> >
> > > On Oct 5, 2026, at 6:59 AM, Matthias van de Meent  wrote:
> > >
> > > On Tue, 29 Sept 2026, 00:29 Greg Burd,  wrote:
> > >>
> > >> Hello hackers,
> > >>
> > >
> > > Hi Greg,
> >
> > Hello Matthias, thanks for taking the time to review.
> >
> > > A few things popped out in this thread, so here's a few comments.
> > >
> > > [...]
> > >
> > >> All these authors and more deserve credit for their hard work, thank
> > >> you.  In the case of ZHeap and Zedstore the ultimate goal was a new table
> > >> AM.  I'm not going to boil that ocean up front, here is where I'm going
> > >> to diverge from those past projects.
> > >
> > > I'd prefer if you didn't boil any oceans in the process of making
> > > contributions.  Not up front is a good start, but please don't do that
> > > later on, either.
> >
> > Ha!  Yeah, oceans are not to be boiled.  Noted.  But really what I was
> > saying is that although I'd included FLUX the intent of this series was
> > to focus on UNDO and FILEOPS and keep HEAP out of it.  Changes to index
> > AMs are essentially no-ops in preparation for a future where a table AM
> > based on UNDO could exist, so arguably they should wait for later too.
> >
> > > [...]
> > >
> > >> If a transaction is in flight and creates a new file and then crashes to
> > >> me it makes sense that after recovery that new file is gone and the
> > >> system is consistent again.
> > >
> > > That very much depends on the type of file created. E.g. WAL files,
> > > SLRU files, and new segments of existing relations should not be
> > > removed just because they were created by a transaction that crashed
> > > or rolled back -- other backends may have have written to those files.
> >
> > Yes, there are exceptions and I should list them.  WAL-logging an undo
> > record for a WAL log change is nuts, never going to work.
> >
> > > Also note that we may want to have UNDO outside transactional
> > > boundaries:  after all, not all DDL is transactional, and I think
> > > there's some gain to be had for e.g. REINDEX CONCURRENTLY; it allows
> > > us to truncate the !indisready index files it leaves behind after a
> > > crash, reducing disk bloat in those cases.
> >
> > Hmmm... I'll have to wrap my head around this one.  UNDO outside of
> > a transaction isn't something I'd sign up for, why not just wrap
> > these changes in transactions?  I get the DDL issue, the reindex
> > one sounds like a good idea.  I'll dig a bit, thanks for opening the
> > door on this.
> >
> > > Side note:  I'd prefer if this change does _not_ mean that unlogged
> > > relations get to WAL-log proportional to data operations.  Undo
> > > logging can be useful, but should not be predicated on WAL if a
> > > tableAM requires UNDO.
> >
> > Good point, I'll need to recheck that I indeed disable UNDO when
> > the relation is unlogged...
> >
> > > [...]
> > >
> > >> Also, I realize that this kind of change takes a lot of time to gain
> > >> traction and adoption into core, if at all.  I'm ready for that, sure
> > >> we're working on v20 now and v19 is inching out the door maybe this
> > >> merges into v25 or maybe it gets shelved along the way for good reason.
> > >> Who knows, but I do know that it's worth the effort to advocate and to
> > >> have a durable record for others interested in it even if it doesn't get
> > >> merged in this time.  I look forward to seeing what happens.  :)
> > >
> > > The title indicates constant-time recovery, but I don't see anything
> > > in this thread that supports this claim.  Could you expand on the
> > > mechanisms you're using to guarantee this?
> >
> > Yes, the target is [1] and possibly [2].  The technique boils down to
> > keeping an "aborted transaction map" (ATM) that you can build during
> > the recovery process which prevents the need for replaying the UNDO
> > records at recovery time to restore physical page information and
> > leaves that for a background worker.
> >
> > > I also don't see how your claimed constant-time rollback can work,
> > > given that the size of a transaction's modified working set is bounded
> > > only by time and the space available to store the database, and that
> > > undoing changes in files can't really be done faster than the
> > > bandwidth of your CPU.  Undoing a set of transaction operations
> > > therefore can't really be constant-time unless you're limiting the
> > > number of undo-able transaction operations, and a limited transaction
> > > size is not really something current users have to consider (and thus,
> > > don't expect).
> >
> > Take a look at the papers, I'll fix up the code and docs and wiki.
> > I'll check back with you on the next patch update and see if I
> > managed to clear this concept up or not. :)
> 
> So, IIUC, the "CTR" here practically means:
> 
>     We use a small checkpoint interval for WAL-logged MVCC-versioned
> REDO-able operations that don't need an online UNDO phase (this is how
> PG works), and store rare UNDO operations in a side stream.

It's how PG works if the table AM is keeping MVCC versions in the pages
that make up the table rather than in the WAL log.  That might be how
SQLServer does it, but my demo FLUX table AM doesn't and it may never
show promise as a viable table AM for production load but that's TBD
at this point.

>     Then we claim that the checkpoint REDO window is time-bounded
> (which is true, but with checkpoint distance -dependent bounds), and
> also claim that the side stream of UNDO operations is also bounded
> (without showing a proof on this).

Yes, time bounded based on checkpoint distance and the per-backend WAL
log that is used by FLUX is that "side stream of UNDO operations".

> I'll have to quote Dodgeball on that: "It's a bold strategy, Cotton.
> Let's see if it pays off for him."

Agreed, and it's exciting to be trying out a different set of
trade-offs than HEAP presents us.  I went into this thinking I was
going to "fix" HEAP, now I admire the careful trade-offs HEAP makes.

UNDO isn't either or, it's both.  Some people need the trade-offs
that an in-place update table AM that uses UNDO for MVCC, others
don't.  Today that door isn't available, I'm just proposing that
there is value in installing the door.  You choose which one you
want.

> And, indeed, the paper's metrics show that "constant time recovery"
> still means "60 seconds of recovery at p99; 180 seconds recovery at
> p99.99", which is a much larger difference than one should expect from
> something that claims to be constant time.

Yes, and it is a bit of a marketing leap to use those words.  I think
I admitted that in my first reply earlier on. :)

> Aside: The paper's claimed recovery time also explicitly does not
> cover the time spent in their equivalent of an autovacuum worker,
> which is tasked with running MVCC cleanup tasks for transactions that
> are in their final state and created dead MVCC version in the table.
> This is OK in principle, but its existence does seem like a critical
> conflict for buidling tableAMs relying on this paper whilst claiming
> that "it does not need vacuum".  Because this paper seems to heavily
> depend on a background task that does VACUUM's job of cleaning up old
> MVCC versions to avoid pushing operations onto the UNDO work queue.

Yes, and no.  Here is where I think I've diverged a bit from SQLServer,
their MVCC cleanup tasks are similar to autovacuum but they need that so
they can do in-page MVCC chains like HEAP does.  I'm not doing that with
FLUX, I'm using the WAL for reconstructing tuples when necessary.

Yes, this setup is n-WAL logs where there is one common one and then one
per-backend for the FLUX table.  That adds I/O and s_b pressure and does
end up writing more than HEAP does (aka "bloat") when you measure that.

As you deftly point out, there's no magic beans.  UNDO is just different
trade-offs.  For FLUX with UNDO you don't have to vacuum, except that you
do need to analyze occasionally and you do have to tend to the creation
and removal of the per-backend WAL files.  So, no it's not free.

The fun part is in the exploration and discovery of a) why HEAP has stood
the test of time, b) where it has been baked into other parts of the
system too deeply, c) how might the trade-offs be rearranged and would
anyone care?

I appreciate the conversation and time you've given to this and I hope
you continue to chime in.  Maybe we'll find a dead-end, or maybe we'll
learn something and open a door that enables a new class of use cases
for Postgres.  Does that make sense?

> Kind regards,
> 
> Matthias van de Meent
> Databricks (https://www.databricks.com)

I'm not promising a miracle, just UNDO.  That may be too much or not
enough and I'm okay with that too.

-greg



Re: UNDO with constant time recovery (CTR)

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
Shihao, Matthias,

Thanks for the careful review of v2.  All three of your reports were
real bugs, and chasing them down led to a much larger round of
stabilization than I'd expected.  v3 is attached, apologies for the length
of this email but there was a lot of churn and this isn't a small set of
changes.


Your three reports:
-------------------

1. Patch-split mistakes (059/061 setting a GUC that only 0005 added; test
   modules only built in 0005).  Fixed: tests live with the feature they
   exercise, and every prefix of the series builds and passes its own tests.

2. CREATE DATABASE crash leaves the directory, for both wal_log and
   file_copy.  Fixed; the destination tree is now owned by FILEOPS and removed
   on abort or crash (recovery/090).  Following it up also found that a loser
   whose UNDO predated the last checkpoint was never rolled back; the
   checkpoint now records in-flight UNDO chains and recovery starts from them
   (test_fileops/005).

3. An ordinary filesystem error turning into a PANIC inside a critical
   section.  Your diagnosis was exact and applied to every immediate
   operation.  The syscall now runs before the critical section, so a failure
   is an ordinary ERROR with the usual message (test_fileops/004 / 016).


Correcting my earlier CTR claim
-------------------------------

Earlier in this thread I said the ATM lets recovery accept connections without
replaying UNDO.  That is not entirely accurate.

 - FLUX table and index UNDO: a live rollback applies the UNDO inline before
   ROLLBACK returns, unless the chain exceeds undo_rollback_overflow_size
   (16 MB) and an undo apply worker has room.  After a crash, recovery queues
   the losers and the per-backend undo workers revert them AFTER the database
   is open, not the ATM.
 - FILEOPS: cluster-wide UNDO for a crash loser is applied BEFORE the database
   opens, linear in the loser's UNDO.

So "no UNDO replay before open" is true only for FLUX table/index UNDO,
via the per-backend workers, and not for FILEOPS.  The cluster-wide
engine keeps UNDO in the WAL stream, so a long transaction pins WAL and
recovery walks loser chains.

"Constant time recovery" (CTR) in the SQL Server sense (a persistent
version store, O(1) abort, bounded recovery) was inspirational, but
recovery as of this version doesn't match that implementation or
claim. So, I have dropped the term and the O(1) claims from the code,
messages, and subject line of this email.


FILEOPS: what it is and is not
------------------------------

I'll admit up front that proper transactional FILEOPS is currently a
narrow transactional layer, but not yet a self-contained crash-atomic
resource manager.  I have stopped calling this "constant time recovery",
that was a mistake, it's bounded and minimal but hardly "constant".

FILEOPS makes the filesystem mutations the server does outside the
buffer manager (CREATE/DROP DATABASE and TABLESPACE directories,
copydir) participate in transactions and in crash recovery, at wal_level
>= replica.  It is NOT a replacement for smgr, and it is NOT a
self-contained crash-atomic resource manager yet, but that is the goal.
Right now here are the honest limitations (also in the README and the
commit message):

 - a commit-time operation (delete/rename/rmdir at commit) is logged after the
   commit record, so a crash in between can lose it (test_fileops/007 TODO);
 - the syscall-before-WAL window;
 - per-transaction, not per-operation, ownership of a crash loser's inverses;
 - nothing for wal_level = minimal.

I've considered integration into the resource manager (self-contained
redo/undo from common WAL, durable intent before commit, per-operation
ownership) but I'm not sure where I'm going to take that idea next.  I'm
open to ideas here.


FLUX
----

FLUX is an in-place-MVCC table access method here not as competition
with HEAP but more an illustration/research/proof-of-concept for an
UNDO-based table AM, not meant for production use (at this time).

Attempts to "make HEAP better by using UNDO" were all unsuccessful; HEAP
represents a set of trade-offs that are proven, well optimized, and
understood by all who use Postgres.

In FLUX, a row keeps its TID for its lifetime; the header carries
heap-shaped xmin/xmax/cid; older versions are reconstructed from the
per-backend UNDO log; row locks live in a shared, on-demand sLog (never
on the tuple).

v3 fixes a long list of correctness bugs this round turned up in testing
and benchmarking against HEAP.  Lost updates and serialization
behaviour, DELETE/UPDATE classification after waiting, CREATE INDEX
CONCURRENTLY, index entries for INCLUDE and non-"equalimage" key
columns, partial-index membership, TOAST reclamation, the visibility
map's WAL ordering, BRIN summarization, and others.  Each is a separate
commit with a test that fails before it and a heap twin.

Two FLUX notes worth stating up front:

 - index-only scans are not used on a FLUX table (a delete-marked index entry
   can carry a key that no longer matches the row until VACUUM);
 - FLUX must never depend on VACUUM for correctness; VACUUM reclaims space and
   freezes for wraparound, as for HEAP.

The sLog that holds row locks allocates nothing at startup (a cluster that
never uses FLUX pays almost nothing) and grows on demand.

Measured on a quiet 64-vCPU host, release builds, pgbench scale 100, all
at 64 concurrent clients; each number is the median of five interleaved
60-second runs, in thousands of transactions per second (higher is
better).  Three FLUX builds are compared against each other, with heap
on the same v3 build as a reference:

 - FLUX/v2    : FLUX as posted in v2 (the old fixed-size row-lock table)
 - FLUX/v3    : FLUX in this series (the on-demand row-lock sLog)
 - heap/v3    : the heap AM on the v3 build, for reference

workload (what each pgbench transaction does)   FLUX/v2  FLUX/v3  heap/v3   v3 vs v2
---------------------------------------------   -------  -------  -------   --------
SELECT FOR UPDATE one row, then UPDATE it         293.0    306.5    359.0     +4.6%
INSERT a child row (foreign-key check on parent)  497.1    505.3    529.9     +1.6%
plain UPDATE (pgbench -N, no row locks)           229.3    243.6    291.7     +6.2%
SELECT 10 rows FOR UPDATE in one transaction      273.8    306.6    285.7    +12.0%
SELECT 100 rows FOR UPDATE in one transaction      20.4     33.0     35.1    +62.1%

So FLUX's row-lock path is at or above the v2 fixed-table store
everywhere, and now beats it by 12% (10-row) and 62% (100-row) at 64
clients.  Fresh-cluster shared memory is +776 KiB over master: the
row-lock store contributes zero startup bytes; the +776 KiB is the
per-backend UNDO structures (~418 KiB) plus the slots for the discard
worker and undo launcher (max_worker_processes 8 -> 12, ~395 KiB).
Those two workers are required for correctness (the discard worker
reclaims undo segments) and hibernate when idle; launching them on first
use is left as future work.


Series
------

 0001  cluster-wide UNDO engine (records in the WAL stream)
 0002  transactional filesystem operations (FILEOPS) backed by UNDO
 0003  route filesystem mutations through FILEOPS
 0004  per-backend UNDO logs
 0005  the ATM, sLog, and logical revert worker
 0006  nbtree: mark aborted index inserts dead via UNDO
 0007  hash: mark aborted index inserts dead via UNDO
 0008  nbtree: in-place delete-marking for stable-TID UPDATE
 0009  tableam: let an AM declare that UPDATE keeps a row's TID
 0010  executor: keep the pre-update row of an in-place UPDATE
 0011  EvalPlanQual: fetch an in-place AM's reference rows with the query snapshot
 0012  AFTER triggers: queue an in-place AM's row images with the event
 0013  logical replication: pre-check unique keys an in-place UPDATE changes
 0014  tableam: SO_RETURN_DELETED, and update_deleted detection for any AM
 0015  tableam: let a block AM's size estimate use its own default fillfactor
 0016  tableam: let REPACK (CONCURRENTLY) accept any AM whose changes are decoded
 0017  vacuum: add parallel_vacuum_set_index_stats() and a bulkdel injection point
 0018  pg_visibility: refuse tables of other table AMs in the tuple checks
 0019  the FLUX in-place-MVCC table access method
 0020  benchmarks: heap vs FLUX

The 0009-0018 commits are heap-neutral preparatory changes to the table-AM,
executor, trigger, EvalPlanQual, logical-replication, VACUUM and pg_visibility
interfaces; each is a no-op for heap and for any AM that does not opt in, and
all are ordered before 0019 (FLUX), which is the first commit that uses them.

Patches
-------

0001  Add a cluster-wide UNDO engine with records in the WAL stream
      The UNDO substrate: records live in the common WAL stream; crash recovery
      reverts loser transactions' structural changes through a recovery pass.
      Changes since v2: 6 items (unused AM prepare hook removed; headerscheck
      skips undormgrlist.h; recovery-model docs made accurate; buffer content
      locks released before inline abort UNDO; failed-abort WAL-hold claim
      corrected; UNDO docs promoted to a chapter).

0002  Add transactional filesystem operations (FILEOPS) backed by UNDO
      WAL resource manager (RM_FILEOPS_ID) making structural filesystem
      mutations crash-safe and rollback-safe; AtPrepare path for 2PC.
      Changes since v2: report apply failures as failures; remove obsolete UNDO
      file cleanup. Tests: drop logical_revert_naptime in 063/061; show a crash
      right after commit loses deferred ops.

0003  Route filesystem mutations through FILEOPS
      Wire in-tree DDL/storage callers (CREATE/DROP DATABASE, TABLESPACE,
      copydir) through the FILEOPS API.  (No "Changes since v2" block.)

0004  Add per-backend UNDO logs
      Per-backend UNDO logs and the undo apply/discard workers; the engine FLUX
      table/index UNDO reverts crash losers from, after the database opens.
      Changes since v2: 38 items (2PC rollback chains; subxact undo dispatch;
      non-permanent/temp undo handling; 3-page record spanning; FPIs on undo
      pages; snapshot-limited recovery start; project formatting + pgperltidy).

0005  Add the ATM, sLog, and logical revert worker
      The aborted-transaction map, the on-demand sLog row-lock store, and the
      logical revert worker.
      Changes since v2: 24 items + 3 tests (retention report; inline UNDO always
      for non-index; new-database dir removed on abort/crash; roll back
      in-flight UNDO preceding the checkpoint; prepared row locks restored
      without clobbering owners; "a cluster that never uses UNDO costs what
      master does").

0006  nbtree: mark aborted index inserts dead via UNDO
      Changes since v2: 22 items + 2 tests (flush index UNDO before commit
      record; newest-first apply in crash recovery; CLR redo consistency-checked;
      index UNDO applied inline only).

0007  hash: mark aborted index inserts dead via UNDO
      Changes since v2: 14 items + 1 test (restore UNDO abort ordering; persist
      FILEOPS ownership for deferred crash losers; dead-tuples hint on hash
      rollback; PANIC only when an inverse cannot be made durable).

0008  nbtree: support in-place delete-marking for stable-TID UPDATE
      Changes since v2: 11 items + 1 test (uniqueness check asks the AM about a
      delete-marked entry; atomic delete-mark of a full leaf via replace split;
      amcheck handles delete-marked entries; tombstone trailer room).

0009  [prep] tableam: let an AM declare that UPDATE keeps a row's TID
0010  [prep] executor: keep the pre-update row of an in-place UPDATE
0011  [prep] EvalPlanQual: fetch an in-place AM's reference rows with the query
      snapshot
0012  [prep] AFTER triggers: queue an in-place AM's row images with the event
0013  [prep] logical replication: pre-check unique keys an in-place UPDATE changes
0014  [prep] tableam: SO_RETURN_DELETED, and update_deleted detection for any AM
0015  [prep] tableam: let a block AM's size estimate use its own default fillfactor
0016  [prep] tableam: let REPACK (CONCURRENTLY) accept any AM whose changes are
      decoded
      (adds TableAmRoutine.am_logical_decoding; REPACK tests it instead of
       naming heap.)
0017  [prep] vacuum: add parallel_vacuum_set_index_stats() and a bulkdel injection
      point
0018  [prep] pg_visibility: refuse tables of other table AMs in the tuple checks
      (0009-0018 have no "Changes since v2" block except 0016; they are the new
       heap-neutral interface preparation split out of the FLUX commit.)

0019  Add the FLUX in-place-MVCC table access method
      In-place MVCC table AM: a row keeps its TID; heap-shaped xmin/xmax/cid in
      the header; older versions from the per-backend UNDO log; row locks in the
      shared on-demand sLog, never on the tuple.
      Changes since v2: 60+ items (invisible aborted writers; idempotent UNDO
      keyed on version; helping; TOAST supersede; VACUUM reclaims aborted-INSERT
      rows and truncates the whole empty tail; tombstone-removal horizon
      reasoning; scan slots own a copy under a writer-excluding lock; VACUUM
      never moves a live row; row locks not held per-row until commit;
      user_catalog_table refused; project formatting + pgperltidy).

0020  Benchmarks: HEAP vs FLUX
      Benchmark scaffolding comparing heap and FLUX. (No "Changes since v2".)


Changes since v2 (series-level)
-------------------------------
 - The three v2 review reports (patch-split mistakes; CREATE DATABASE crash
   leaving the directory; a filesystem error PANICking in a critical section)
   are fixed; see the cover letter.
 - The "constant time recovery / CTR" framing and the O(1) claims are dropped;
   the README states the real recovery model.
 - Rebased from the v2 base onto current origin/master (72b916a20db), 99
   upstream commits of churn resolved; 4 merge conflicts, all in test-list /
   docs files (recovery test 058/059 renumbered to 062/063 around upstream's
   new 058/059; repack.sgml restructure; test_decoding + injection_points spec
   lists), no code-logic conflicts.
 - Full release gate green on the rebased tip (see cover-letter status block).

Review of 0001-0003 is most useful; I'd especially value a second look
at the FILEOPS abort-record ordering and the checkpoint in-flight record
in 0001.

best.

-greg

Re: UNDO with constant time recovery (CTR)

От:
Matthias van de Meent <boekewurm+postgres@gmail.com>
Дата:
On Tue, 6 Oct 2026 at 03:58, Greg Burd  wrote:
>
>
>
> On Monday, October 5th, 2026 at 5:23 PM, Matthias van de Meent  wrote:
>
> > On Mon, 5 Oct 2026 at 21:49, Greg Burd  wrote:
> > >
> > >
> > > > On Oct 5, 2026, at 6:59 AM, Matthias van de Meent  wrote:
> > > >
> > > > On Tue, 29 Sept 2026, 00:29 Greg Burd,  wrote:
> > > >>
> > > >> Hello hackers,
> > > >>
> > > >
> > > > Hi Greg,
> > >
> > > Hello Matthias, thanks for taking the time to review.
> > >
> > > > A few things popped out in this thread, so here's a few comments.
> > > >
> > > > [...]
> > > >
> > > >> All these authors and more deserve credit for their hard work, thank
> > > >> you.  In the case of ZHeap and Zedstore the ultimate goal was a new table
> > > >> AM.  I'm not going to boil that ocean up front, here is where I'm going
> > > >> to diverge from those past projects.
> > > >
> > > > I'd prefer if you didn't boil any oceans in the process of making
> > > > contributions.  Not up front is a good start, but please don't do that
> > > > later on, either.
> > >
> > > Ha!  Yeah, oceans are not to be boiled.  Noted.  But really what I was
> > > saying is that although I'd included FLUX the intent of this series was
> > > to focus on UNDO and FILEOPS and keep HEAP out of it.  Changes to index
> > > AMs are essentially no-ops in preparation for a future where a table AM
> > > based on UNDO could exist, so arguably they should wait for later too.
> > >
> > > > [...]
> > > >
> > > >> If a transaction is in flight and creates a new file and then crashes to
> > > >> me it makes sense that after recovery that new file is gone and the
> > > >> system is consistent again.
> > > >
> > > > That very much depends on the type of file created. E.g. WAL files,
> > > > SLRU files, and new segments of existing relations should not be
> > > > removed just because they were created by a transaction that crashed
> > > > or rolled back -- other backends may have have written to those files.
> > >
> > > Yes, there are exceptions and I should list them.  WAL-logging an undo
> > > record for a WAL log change is nuts, never going to work.
> > >
> > > > Also note that we may want to have UNDO outside transactional
> > > > boundaries:  after all, not all DDL is transactional, and I think
> > > > there's some gain to be had for e.g. REINDEX CONCURRENTLY; it allows
> > > > us to truncate the !indisready index files it leaves behind after a
> > > > crash, reducing disk bloat in those cases.
> > >
> > > Hmmm... I'll have to wrap my head around this one.  UNDO outside of
> > > a transaction isn't something I'd sign up for, why not just wrap
> > > these changes in transactions?  I get the DDL issue, the reindex
> > > one sounds like a good idea.  I'll dig a bit, thanks for opening the
> > > door on this.
> > >
> > > > Side note:  I'd prefer if this change does _not_ mean that unlogged
> > > > relations get to WAL-log proportional to data operations.  Undo
> > > > logging can be useful, but should not be predicated on WAL if a
> > > > tableAM requires UNDO.
> > >
> > > Good point, I'll need to recheck that I indeed disable UNDO when
> > > the relation is unlogged...
> > >
> > > > [...]
> > > >
> > > >> Also, I realize that this kind of change takes a lot of time to gain
> > > >> traction and adoption into core, if at all.  I'm ready for that, sure
> > > >> we're working on v20 now and v19 is inching out the door maybe this
> > > >> merges into v25 or maybe it gets shelved along the way for good reason.
> > > >> Who knows, but I do know that it's worth the effort to advocate and to
> > > >> have a durable record for others interested in it even if it doesn't get
> > > >> merged in this time.  I look forward to seeing what happens.  :)
> > > >
> > > > The title indicates constant-time recovery, but I don't see anything
> > > > in this thread that supports this claim.  Could you expand on the
> > > > mechanisms you're using to guarantee this?
> > >
> > > Yes, the target is [1] and possibly [2].  The technique boils down to
> > > keeping an "aborted transaction map" (ATM) that you can build during
> > > the recovery process which prevents the need for replaying the UNDO
> > > records at recovery time to restore physical page information and
> > > leaves that for a background worker.
> > >
> > > > I also don't see how your claimed constant-time rollback can work,
> > > > given that the size of a transaction's modified working set is bounded
> > > > only by time and the space available to store the database, and that
> > > > undoing changes in files can't really be done faster than the
> > > > bandwidth of your CPU.  Undoing a set of transaction operations
> > > > therefore can't really be constant-time unless you're limiting the
> > > > number of undo-able transaction operations, and a limited transaction
> > > > size is not really something current users have to consider (and thus,
> > > > don't expect).
> > >
> > > Take a look at the papers, I'll fix up the code and docs and wiki.
> > > I'll check back with you on the next patch update and see if I
> > > managed to clear this concept up or not. :)
> >
> > So, IIUC, the "CTR" here practically means:
> >
> >     We use a small checkpoint interval for WAL-logged MVCC-versioned
> > REDO-able operations that don't need an online UNDO phase (this is how
> > PG works), and store rare UNDO operations in a side stream.
>
> It's how PG works if the table AM is keeping MVCC versions in the pages
> that make up the table rather than in the WAL log.  That might be how
> SQLServer does it, but my demo FLUX table AM doesn't and it may never
> show promise as a viable table AM for production load but that's TBD
> at this point.

If your FLUX table doesn't, then it doesn't follow CTR, so using the
paper's name will only lead to confuse readers.

> >     Then we claim that the checkpoint REDO window is time-bounded
> > (which is true, but with checkpoint distance -dependent bounds), and
> > also claim that the side stream of UNDO operations is also bounded
> > (without showing a proof on this).
>
> Yes, time bounded based on checkpoint distance and the per-backend WAL
> log that is used by FLUX is that "side stream of UNDO operations".

But that side stream is not limited in any way I can see.

> > I'll have to quote Dodgeball on that: "It's a bold strategy, Cotton.
> > Let's see if it pays off for him."
>
> Agreed, and it's exciting to be trying out a different set of
> trade-offs than HEAP presents us.  I went into this thinking I was
> going to "fix" HEAP, now I admire the careful trade-offs HEAP makes.
>
> UNDO isn't either or, it's both.  Some people need the trade-offs
> that an in-place update table AM that uses UNDO for MVCC, others
> don't.  Today that door isn't available, I'm just proposing that
> there is value in installing the door.  You choose which one you
> want.

I'm all for installing doors to rooms that need more doors, but let's
first take a look at whether the wall you're installing it into is
load-bearing before you start deconstructing it to make space for the
door, or bulldoze the whole house because you think the best place to
put the door is where the hearth currently is located.

> > And, indeed, the paper's metrics show that "constant time recovery"
> > still means "60 seconds of recovery at p99; 180 seconds recovery at
> > p99.99", which is a much larger difference than one should expect from
> > something that claims to be constant time.
>
> Yes, and it is a bit of a marketing leap to use those words.

I'd expected that we didn't use papers based on their marketing
claims, but on their true merits.  If you take the constant-time
recovery out of CTR you're not left with much, if anything.

>  I think
> I admitted that in my first reply earlier on. :)

Hmm, maybe it was my then-tired mind not picking up on it, because it
wasn't clear to me.  I really dislike marketing claims that can't be
backed by hard numbers.

> > Aside: The paper's claimed recovery time also explicitly does not
> > cover the time spent in their equivalent of an autovacuum worker,
> > which is tasked with running MVCC cleanup tasks for transactions that
> > are in their final state and created dead MVCC version in the table.
> > This is OK in principle, but its existence does seem like a critical
> > conflict for buidling tableAMs relying on this paper whilst claiming
> > that "it does not need vacuum".  Because this paper seems to heavily
> > depend on a background task that does VACUUM's job of cleaning up old
> > MVCC versions to avoid pushing operations onto the UNDO work queue.
>
> Yes, and no.  Here is where I think I've diverged a bit from SQLServer,
> their MVCC cleanup tasks are similar to autovacuum but they need that so
> they can do in-page MVCC chains like HEAP does.

I'm fairly sure they need it so they can get rid of rolled back
transactions and other detritis produced by MVCC, regardless of the
MVCC storage approach.  Heck, even MySQL has maintenance workers for
this.

>  I'm not doing that with
> FLUX, I'm using the WAL for reconstructing tuples when necessary.

That's going to cause issues with retention of MVCC data.  Right now,
we only need up to two times max_wal_size, and even then users find a
way to drop the contents of the pg_wal directory.

> Yes, this setup is n-WAL logs where there is one common one and then one
> per-backend for the FLUX table.  That adds I/O and s_b pressure and does
> end up writing more than HEAP does (aka "bloat") when you measure that.
>
> As you deftly point out, there's no magic beans.  UNDO is just different
> trade-offs.  For FLUX with UNDO you don't have to vacuum, except that you
> do need to analyze occasionally and you do have to tend to the creation
> and removal of the per-backend WAL files.  So, no it's not free.

If not with vacuum, how do you recover from e.g. transaction rollback,
or lost connections?

> The fun part is in the exploration and discovery of a) why HEAP has stood
> the test of time, b) where it has been baked into other parts of the
> system too deeply, c) how might the trade-offs be rearranged and would
> anyone care?

Please allow me to find fun in different things.

> I appreciate the conversation and time you've given to this and I hope
> you continue to chime in.  Maybe we'll find a dead-end, or maybe we'll
> learn something and open a door that enables a new class of use cases
> for Postgres.  Does that make sense?

Maybe.  But I don't think the -hackers list is a good place to
prototype changes many layers deep, with new MB-sized patches every
day, without that thread explictly describing the status of the
patchset as experimental.  Having an end goal in mind is great, but I
can't (and won't) review MB-sized patchsets that do too many things at
once, at least not to the detail that would be required for it to get
committed.  FYI, based on the patch headers, I think this patchset is
trying to do too much at once by a factor of _at least_ 3.


Kind regards,

Matthias van de Meent
Databricks (https://www.databricks.com)


FAQ