Re: Direct TOAST v2, faster, smaller and no migration needed
Re: Direct TOAST v2, faster, smaller and no migration needed
От:
Matthias van de Meent <boekewurm+postgres@gmail.com>
Дата:
On Mon, 7 Sept 2026 at 08:51, Hannu Krosing wrote: > > On Mon, Sep 7, 2026 at 5:13 AM Michael Paquier wrote: > > > > A few things that come on top of my mind: [...] > > - Lock contention and concurrency. A btree page for a TOAST table in > > cache is able to hold hundreds of references to various entries. > > Fair point. > The reasons why I think it s still faster are: > 1. the case for tiny toasted values will go directly to the page. > Currently "tiny" is one 2k chunk , but could be expanded to full page > as a follow-up > 2. the case with just a small number of chunks will likely have the > data and tid array(s) in the same page, or pages very cloes to each > other. > 3. for huge toasted values the full tid array is constructed before > the actual data retrieval starts, and it is done in order of magnitude > less page accesses than getting the same data from a b-tree index > takes. Do you have your notes on this? I can see why you'd claim fewer page accesses, but an order of magnitude is a very large claim; I'm getting to a ~5x reduction at best. With standard packing of OID indexes, I'd expect ~ 290 TIDs per page (at 20 bytes/entry, 70% fillfactor), with up to 25% more (to ~ 350/page) if the btree split algo selects the split point nicely. For a TID array stored in a heap tuple, you'll be hard-pressed to fit more than 1356 (uncompressed) TIDs on a page. So, to find the same number of TIDs the index will read 4-5x as many pages, but that's not a full order of magnitude, and only with current indexing techniques. I think it's feasible for btree to further optimize its storage format of toast -like fixed-size nonnull column definitions, allowing for more entries per page. > > This is ensured by adding two new concepts to TOAST tables, even in > > the existing TOAST 4-byte case: two new attributes and a partial > > index. The existing attribute layer is moot when using one (4-byte > > value) or the other (direct). This is a waste, and unlikely free. > > The addition of a new partial index does not help much in that. > > It is not a *new* partial index, but the current PK is replaced with > this. In case of online conversion, the current PK constraint is > converted into this in-place. Don't you need a SHARE lock to build (replace) indexes? > > I understand that you've written that this way to claim a cheap rewrite > > when switching over by manipulating data later on on upgrades, but > > that does not sound acceptable here. > > You do not need to manipulate data at all if you are ok with current > data staying accessed via the 4-byte OID and index. No, but then you've not really switched over your toast. > > Finally, and the biggest elephant in the room here by far.. VACUUM > > FULL, CLUSTER and REPACK *have* to be forbidden, because on rewrite > > each command rewrites the tids in the parent. > > They are only forbidden directly on the toast table, they work fine > when run on main table But the independent repack-ability of toast tables is a very valuable feature. Main tables have indexes that may be very expensive to rebuild. Yes, CONCURRENTLY could help, but it'll still take a possibly huge amount of resources, in time, CPU, memory, disk, IO. Repacking the toast table separately solves bloat issues in the toast table, and does not require the main table to be rebuilt, avoiding the related resource consumptions of index builds etc. > and they also result in a clustered order > synchronized with main table, which is not the case when running on > toast table directly with the current design Yes, repacking the toast table won't reorder the toast table to heap order, but in my humble opinion that's OK; just de-bloating the toast table and index is enough for some workloads. > > That's a legal > > defensive set of commands because it is possible to reclaim bloat from > > TOAST relations directly, and I doubt that we'd *ever* want to drop > > this property, especially based on the benchmark claim of upthread. > > If you have a workload that updates toasted columns this results in > these being sprinkled all over the toast table, with random oids, so > even CLUSTER will not put them in the same order as main table. What do you mean by sprinkled all over and random OIDs? Toast IDs that are generated at about the same time will generally be closely related, and after CLUSTER these will be close together in the toast table, for both OID (very likely) and OID8 (practically guaranteed). They will definitely be in OID order, so what is the sprinkling randomness about? > This is why you want to run REPACK on the main table if you need to > recover space AND also care about performance. > In my tests autovacuum kept the direct toast table in shape more > efficiently, most likely because it could skip the expensive index > cleanup phase, so there was less bloat accumulating. How do you fit these claims together? 1. "zero-downtime / zero-migration switch to direct toast (and back)" (from the start of the thread); 2. No index cleanup phase If you can do a zero-migration change, old data will still have old pointers, and those must be looked up through the index. Once a table has an index, its vacuum MUST apply an index cleanup phase, lest it contain any references to LP_DEAD line pointers still present in the table. Note that LP_DEAD entries don't carry information about which index(es) do or don't contain references to that item, so you can't distinguish between included in and excluded from the index -- all dead items must be processed. > > A > > worst thing to me is that this seems to entirely disable their use due > > to this in v2-0004, cluster_rel() or cluster.c: > > + if (OldHeap->rd_rel->relkind == RELKIND_TOASTVALUE) > > [..,] > > + if (OldHeap->rd_att->natts >= 4 && > > > > The two new attributes are added *unconditionally*. > > Yes, but they are not used if you keep using only 4-byte OIDs. In that > case they only appear in the catalog tables. That's not accurate; these columns will hold NULL values, which means they'll bloat OID-toast tuples with a NULL bitmap, which will be one MAXALIGN quantum in size in this table definition. > > Another thing that is really disturbing to me is that using tids > > lowers the protection regarding TOAST lookups. A TOAST value acts a > > second barrier of protection if we miss a chunk, and we have a long > > history of bugs in this area (spoiler: we still had two recent > > discussions about the same set of issues for very old problems, still > > unresolved). Relying on only a get_toast_snapshot() and a bare TID > > lookup neither verifies nor enforces that the chunk we have retrieved > > is the correct one. > > Are we really re-checking the OID in the chunk tuple in current implementation. > > I don't think we re-check the OID in the chunk tuple for b-tree index lookups. No, we don't recheck the valueid in the heaptuple. However, we do check that the chunk counter matches the expected values, and that's something that won't be possible in the direct toast design -- there is nothing in the toast pointer nor the toast tuple that links it to its own identity, especially not outside the scope of MVCC snapshots. > > give the option for new tables to choose this method > > (for the reasons listed in the last two paragraphs, I guess no anyway, > > but that's what I would recommend if following up). > > The main reason you may want to REPACK *only* the toast table is that > it currently behaves badly, partly because of expensive toast index > cleanups. > > If you want performance back, you want to REPACK the main table, which > fixes the random placement of toasted field problem. It is very feasible for the main table to be packed normally, whilst the toast table becomes very bloated; this happens frequently when large toasted columns get updated every once in a while with vacuum and/or page pruning running just frequently enough to allow the main table's tuple to fit back on the same page. REPACKing the main table requires more locks and possibly much more time than just repacking the toast table (one btree index rebuild vs numerous arbitrarily defined index rebuilds). I don't think trading the independent repack-ability of a toast table for a bit of performance with small toasted values is a reasonable tradeoff for every user. > ## In conclusion: > > I still think that these three goals > - zero-downtime upgrade > - less space used > - faster performance > are equally important and should be tackled together. > > As for your performance concerns, can you point me to use cases where > you think the current oid4 can be faster? > It does not have to be very detailed, just a general workload description helps. I'd consider huge toasted values as a case where index lookups can be faster, because it automatically gains the benefits of performance improvements in the index lookup path. The Direct Toast path needs to manually build this feature. And please test the performance difference between repacking a bloated toast table vs repacking its main table with expensive-to-build indexes (e.g. several gin on jsonb, pg_trgm with large text, HNSW, etc.). I think the cost of fixing bloat in the toast table will be much lower than repacking the main table+indexes with it. > I will run some tests to see if extra checks for direct toast and > index predicate has a measurable effect in oid4 path. Note that PG currently has no builtin partial index definitions in its catalogs, they're only present on user-controlled table definitions. The suggested exclusion of "direct toast" values from the toast index would be a first, and I'm not sure that's something that we want. Kind regards, Matthias van de Meent Databricks (https://www.databricks.com)
Re: Direct TOAST v2, faster, smaller and no migration needed
On Tue, Sep 29, 2026 at 02:18:41PM +0200, Matthias van de Meent wrote: > But the independent repack-ability of toast tables is a very valuable > feature. Main tables have indexes that may be very expensive to > rebuild. Yes, CONCURRENTLY could help, but it'll still take a > possibly huge amount of resources, in time, CPU, memory, disk, IO. > Repacking the toast table separately solves bloat issues in the toast > table, and does not require the main table to be rebuilt, avoiding the > related resource consumptions of index builds etc. Note that TOAST-only nightly VACUUMs can be quite common for some workloads, a reason why VACUUM (PROCESS_TOAST) exists so as we can clean up only the underlying TOAST table. I do not see enough arguments in favor of dropping this kind of properties that many people rely on, based on only the claims posted on this thread. That's just too much risk compared to the potential reward. > No, we don't recheck the valueid in the heaptuple. However, we do > check that the chunk counter matches the expected values, and that's > something that won't be possible in the direct toast design -- there > is nothing in the toast pointer nor the toast tuple that links it to > its own identity, especially not outside the scope of MVCC snapshots. Yes, we've relied on the concept of TOAST tuple "identity" heavily for 20-ish years. You could introduce a new behavior based on tids as an opt-in, I guess, leaving the default 4-bytes be, giving access to tid-based access tables for newly-created TOAST tables. Anyway, claiming that this proposal should enforce a new behavior across the board for everything is not something I can vouch for. I get the cheap rewrite argument with the addition of the partial index, but no solution has magical properties; there are always two sides of the coin, and we have to think about both sides. Using tids for lookups has benefits in some cases, clearly, just claiming that it's always beneficial for every kind of workload is something I find very hard to believe. The decision to make impossible TOAST-based VACUUMs is one downside that I do not and will not underestimate, for one. I cannot speak for other committers, but at least that's one committer opinion. My opinion can of course be overruled, it happens a lot. Another concept Greg Burd has been mentioning to me is overflow pages, used by some other systems: keep all the chunks in heap, with tid redirections. That kind of mimics some of the builds out there where folks compile the code with larger base page sizes to avoid the TOAST lookups, for workloads where the blobs are large enough to be in TOAST but could fit on a page if made larger. It has its own set of advantages and disadvantages as well, like any other approach. Back to the two sides of the coin. -- Michael
Re: Direct TOAST v2, faster, smaller and no migration needed
От:
Hannu Krosing <hannuk@google.com>
Дата:
Adding back the list and other recipients again
On Wed, Sep 30, 2026 at 4:56 AM Michael Paquier wrote:
>
> On Tue, Sep 29, 2026 at 02:18:41PM +0200, Matthias van de Meent wrote:
> > But the independent repack-ability of toast tables is a very valuable
> > feature. Main tables have indexes that may be very expensive to
> > rebuild. Yes, CONCURRENTLY could help, but it'll still take a
> > possibly huge amount of resources, in time, CPU, memory, disk, IO.
> > Repacking the toast table separately solves bloat issues in the toast
> > table, and does not require the main table to be rebuilt, avoiding the
> > related resource consumptions of index builds etc.
>
> Note that TOAST-only nightly VACUUMs can be quite common for some
> workloads, a reason why VACUUM (PROCESS_TOAST) exists so as we can
> clean up only the underlying TOAST table. I do not see enough
> arguments in favor of dropping this kind of properties that many
> people rely on, based on only the claims posted on this thread.
> That's just too much risk compared to the potential reward.
I have a patch to treat deleted Direct TOAST chunks similar to HOT pages and
prune them to LP_UNUSED on access, together with page map updates, so
you can get to a steady state without running even autovacuum.
This is now possible because there is no index cleanup needed.
> > No, we don't recheck the valueid in the heaptuple. However, we do
> > check that the chunk counter matches the expected values, and that's
> > something that won't be possible in the direct toast design -- there
> > is nothing in the toast pointer nor the toast tuple that links it to
> > its own identity, especially not outside the scope of MVCC snapshots.
>
> Yes, we've relied on the concept of TOAST tuple "identity" heavily for
> 20-ish years.
>
> You could introduce a new behavior based on tids as an opt-in, I
> guess, leaving the default 4-bytes be, giving access to tid-based
> access tables for newly-created TOAST tables.
The latest patch series does this for both oid and oi8 TOAST.
And it has been something you can turn on and off via ALTER TABLE ...
(toast_flavour = direct)
It can be turned on and off any time you like, as both types of toas
can live together.
> Anyway, claiming that this proposal should enforce a new behavior
> across the board for everything is not something I can vouch for.
It does not force anything, is controlled by a dynamic table storage
parameter toast_flavour
And we probably should also allow toast_flavor :)
Patch 2: Add Direct TOAST catalog, GUC, and reloptions infrastructure
Defines struct varatt_direct and VARTAG_DIRECT in varatt.h. Adds the
default_toast_flavour GUC ('plain' | 'direct', default 'plain') and the
table storage parameter toast_flavour. Extends create_toast_table() to add
chunk_tids (tid[]) and chunk_tid_offsets (int8[]) to TOAST relations and
creates the partial index predicate (WHERE chunk_id IS NOT NULL).
> I get the cheap rewrite argument with the addition of the partial index,
> but no solution has magical properties; there are always two sides of
> the coin, and we have to think about both sides. Using tids for
> lookups has benefits in some cases, clearly, just claiming that it's
> always beneficial for every kind of workload is something I find very
> hard to believe.
That's why I have asked you to find a counterexample :)
> The decision to make impossible TOAST-based VACUUMs
> is one downside that I do not and will not underestimate, for one. I
> cannot speak for other committers, but at least that's one committer
> opinion. My opinion can of course be overruled, it happens a lot.
For a VACUUM FULL equivalent you can still do REPACK on main table
which has the upside of clustering the toast values in table order
And the normal vacuum is made drastically faster as it can skip the
index scan and prune tuples immediately.
> Another concept Greg Burd has been mentioning to me is overflow pages,
> used by some other systems: keep all the chunks in heap, with tid
> redirections.
Yes, this was actually the original Ingres design from 1976, see page 204
in https://www.engineering.upenn.edu/~zives/cis650/papers/INGRES.PDF
The downside is that it would updates more expensive when the toasted
values are not updated.
> That kind of mimics some of the builds out there where
> folks compile the code with larger base page sizes to avoid the TOAST
> lookups, for workloads where the blobs are large enough to be in TOAST
> but could fit on a page if made larger.
The other page sizes seem to be largely neglected.
Currently some tests fail and someone told me that the b-tree still
would fill the larger pages only up to 8k :(
I made a weak attempt to set up a build farm animal to test 16k ad 32k
pages but never got my buildfarm key back from the registraion form.
> It has its own set of
> advantages and disadvantages as well, like any other approach. Back
> to the two sides of the coin.
Agreed, without more invasive changes larger pages will cause at least
more read and write amplification for sparse accesses to just mention
one downside.
Re: Direct TOAST v2, faster, smaller and no migration needed
От:
Hannu Krosing <hannuk@google.com>
Дата:
Adding also the other original recipients
On Wed, Sep 30, 2026 at 10:58 AM Hannu Krosing wrote:
>
> On Tue, Sep 29, 2026 at 2:19 PM Matthias van de Meent
> wrote:
> >
> > On Mon, 7 Sept 2026 at 08:51, Hannu Krosing wrote:
> > >
> > > On Mon, Sep 7, 2026 at 5:13 AM Michael Paquier wrote:
> > > >
> > > > A few things that come on top of my mind:
> > [...]
> > > > - Lock contention and concurrency. A btree page for a TOAST table in
> > > > cache is able to hold hundreds of references to various entries.
> > >
> > > Fair point.
> > > The reasons why I think it s still faster are:
> > > 1. the case for tiny toasted values will go directly to the page.
> > > Currently "tiny" is one 2k chunk , but could be expanded to full page
> > > as a follow-up
> > > 2. the case with just a small number of chunks will likely have the
> > > data and tid array(s) in the same page, or pages very cloes to each
> > > other.
> > > 3. for huge toasted values the full tid array is constructed before
> > > the actual data retrieval starts, and it is done in order of magnitude
> > less page accesses than getting the same data from a b-tree index
> > takes.
>
> Do you have your notes on this? I can see why you'd claim fewer page
> accesses, but an order of magnitude is a very large claim; I'm getting
> to a ~5x reduction at best.
>
> With standard packing of OID indexes, I'd expect ~ 290 TIDs per page
> (at 20 bytes/entry, 70% fillfactor), with up to 25% more (to ~
> 350/page) if the btree split algo selects the split point nicely. For
> a TID array stored in a heap tuple, you'll be hard-pressed to fit more
> than 1356 (uncompressed) TIDs on a page. So, to find the same number
> of TIDs the index will read 4-5x as many pages, but that's not a full
> order of magnitude, and only with current indexing techniques.
Yeah, it was 2 binary orders of magnitude for normal use when
everything fits in memory
The extreme cases only surface when you the toast index does not fit
in memory and index part heavily dominates the lookups. That is when
you have small toast chunks.
> I think it's feasible for btree to further optimize its storage format
> of toast -like fixed-size nonnull column definitions, allowing for
> more entries per page.
This will still not address the need to do index cleanups when pruning
deleted toast, which avoiding the index entirely does.
> > > > This is ensured by adding two new concepts to TOAST tables, even in
> > > > the existing TOAST 4-byte case: two new attributes and a partial
> > > > index. The existing attribute layer is moot when using one (4-byte
> > > > value) or the other (direct). This is a waste, and unlikely free.
> > > > The addition of a new partial index does not help much in that.
> > >
> > > It is not a *new* partial index, but the current PK is replaced with
> > > this. In case of online conversion, the current PK constraint is
> > > converted into this in-place.
> >
> > Don't you need a SHARE lock to build (replace) indexes?
You need an exclusive lock for less than a millisecond to convert the
index in-place.
It is a metadata only change.
> > > I understand that you've written that this way to claim a cheap rewrite
> > > when switching over by manipulating data later on on upgrades, but
> > > that does not sound acceptable here.
> >
> > You do not need to manipulate data at all if you are ok with current
> > data staying accessed via the 4-byte OID and index.
>
> No, but then you've not really switched over your toast.
You can rewrite all the toast using REPACK CONCURRENTLY if you want
all your toasted data to use Direct TOAST.
> > > Finally, and the biggest elephant in the room here by far.. VACUUM
> > > FULL, CLUSTER and REPACK *have* to be forbidden, because on rewrite
> > > each command rewrites the tids in the parent.
> >
> > They are only forbidden directly on the toast table, they work fine
> > when run on main table
>
> But the independent repack-ability of toast tables is a very valuable
> feature. Main tables have indexes that may be very expensive to
> rebuild. Yes, CONCURRENTLY could help, but it'll still take a
> possibly huge amount of resources, in time, CPU, memory, disk, IO.
> Repacking the toast table separately solves bloat issues in the toast
> table, and does not require the main table to be rebuilt, avoiding the
> related resource consumptions of index builds etc.
Good Point. This is an issue when the main table which is much larger
and more expensive index-wise than toast and toast is already messed up
(Though in this case I would expect the main problem to be the main
table, not toast)
If toast is not messed up, in-line pruning should keep the TOAST table
growth in check.
I will look at adding REPACK TOAST CONCURRENTLY which only clusters toast.
The current Direct TOAST design still has the toast table oid in
varlena pointer for which the only justifyable use is having multiple
toast tables active concurrently.
> > and they also result in a clustered order
> > synchronized with main table, which is not the case when running on
> > toast table directly with the current design
>
> Yes, repacking the toast table won't reorder the toast table to heap
> order, but in my humble opinion that's OK; just de-bloating the toast
> table and index is enough for some workloads.
It is for some.
And for even more workloads you do not need de-bloating at all, even
with current design.
Direct Toast allows you to not get bloated in the first place because
of inline pruning and really cheap vacuum which needs to jsut look at
dirty pages and fully skip the index cleanup.
> > > That's a legal
> > > defensive set of commands because it is possible to reclaim bloat from
> > > TOAST relations directly, and I doubt that we'd *ever* want to drop
> > > this property, especially based on the benchmark claim of upthread.
> >
> > If you have a workload that updates toasted columns this results in
> > these being sprinkled all over the toast table, with random oids, so
> > even CLUSTER will not put them in the same order as main table.
>
> What do you mean by sprinkled all over and random OIDs?
> Toast IDs that are generated at about the same time will generally be
> closely related, and after CLUSTER these will be close together in the
> toast table, for both OID (very likely) and OID8 (practically
> guaranteed).
>
> They will definitely be in OID order, so what is the
> sprinkling randomness about?
UPDATE will generate a new toasted value with newly allocated oid. If
some fields are updated late then they will not be close.
hannuk=# create table toastme(datum text storage external);
CREATE TABLE
hannuk=# insert into toastme select repeat('abracadabra', 1000);
INSERT 0 1
hannuk=# select pg_column_toast_chunk_id(datum) from toastme ;
pg_column_toast_chunk_id
──────────────────────────
16500
(1 row)
hannuk=# update toastme set datum = repeat('not abracadabra', 1000);
UPDATE 1
hannuk=# select pg_column_toast_chunk_id(datum) from toastme ;
pg_column_toast_chunk_id
──────────────────────────
16501
(1 row)
> > > This is why you want to run REPACK on the main table if you need to
> > > recover space AND also care about performance.
> > > In my tests autovacuum kept the direct toast table in shape more
> > > efficiently, most likely because it could skip the expensive index
> > > cleanup phase, so there was less bloat accumulating.
> >
> > How do you fit these claims together?
> >
> > 1. "zero-downtime / zero-migration switch to direct toast (and back)"
> > (from the start of the thread);
> > 2. No index cleanup phase
> >
> > If you can do a zero-migration change, old data will still have old
> > pointers, and those must be looked up through the index.
> > Once a table has an index, its vacuum MUST apply an index cleanup
> > phase, lest it contain any references to LP_DEAD line pointers still
> > present in the table. Note that LP_DEAD entries don't carry
> > information about which index(es) do or don't contain references to
> > that item, so you can't distinguish between included in and excluded
> > from the index -- all dead items must be processed.
Latest few patch sets have includes a change to pruning which prunes
deleted direct toast chunks to LP_UNUSED directly
So if you have been updating only direct toast pointers there will be
no dead tids collected.
Even if there were some, all dead space from updated direct tuples is
returned to postgresql immediately.
> > > > A
> > > > worst thing to me is that this seems to entirely disable their use due
> > > > to this in v2-0004, cluster_rel() or cluster.c:
> > > > + if (OldHeap->rd_rel->relkind == RELKIND_TOASTVALUE)
> > > > [..,]
> > > > + if (OldHeap->rd_att->natts >= 4 &&
> > > >
> > > > The two new attributes are added *unconditionally*.
> > >
> > > Yes, but they are not used if you keep using only 4-byte OIDs. In that
> > > case they only appear in the catalog tables.
> >
> > That's not accurate; these columns will hold NULL values, which means
> > they'll bloat OID-toast tuples with a NULL bitmap, which will be one
> > MAXALIGN quantum in size in this table definition.
There is always space for one byte of null bitmap after the 23-byte
tuple headers, so up to 8 attributes can have their null bitmap for
free.
AND even now the three user attributes are not declared NOT NULL
hannuk=# select attname, attnotnull from pg_attribute where attrelid =
'pg_toast.pg_toast_826'::regclass;
attname │ attnotnull
────────────┼────────────
tableoid │ t
cmax │ t
xmax │ t
cmin │ t
xmin │ t
ctid │ t
chunk_id │ f
chunk_seq │ f
chunk_data │ f
(9 rows)
> > > > Another thing that is really disturbing to me is that using tids
> > > > lowers the protection regarding TOAST lookups. A TOAST value acts a
> > > > second barrier of protection if we miss a chunk, and we have a long
> > > > history of bugs in this area (spoiler: we still had two recent
> > > > discussions about the same set of issues for very old problems, still
> > > > unresolved). Relying on only a get_toast_snapshot() and a bare TID
> > > > lookup neither verifies nor enforces that the chunk we have retrieved
> > > > is the correct one.
> > >
> > > Are we really re-checking the OID in the chunk tuple in current implementation.
> > >
> > > I don't think we re-check the OID in the chunk tuple for b-tree index lookups.
> >
> > No, we don't recheck the valueid in the heaptuple. However, we do
> > check that the chunk counter matches the expected values, and that's
> > something that won't be possible in the direct toast design -- there
> > is nothing in the toast pointer nor the toast tuple that links it to
> > its own identity, especially not outside the scope of MVCC snapshots.
Do you think it os a valuable property to have ?
As we are not bloating the varlena pointer in case of direct toast, we
could add more info in the cunk for multi-chunk cases
One we have more than one chunk, the overhead from becomes tiny
I am already working on enabling a much richer compression and
encoding options using this - zstd and lz4 dictioonalries, Apache AVRO
encoding, per-chunk compression, etc
> > > > give the option for new tables to choose this method
> > > > (for the reasons listed in the last two paragraphs, I guess no anyway,
> > > > but that's what I would recommend if following up).
> > >
> > > The main reason you may want to REPACK *only* the toast table is that
> > > it currently behaves badly, partly because of expensive toast index
> > > cleanups.
> > >
> > > If you want performance back, you want to REPACK the main table, which
> > > fixes the random placement of toasted field problem.
> >
> > It is very feasible for the main table to be packed normally, whilst
> > the toast table becomes very bloated; this happens frequently when
> > large toasted columns get updated every once in a while with vacuum
> > and/or page pruning running just frequently enough to allow the main
> > table's tuple to fit back on the same page. REPACKing the main table
> > requires more locks and possibly much more time than just repacking
> > the toast table (one btree index rebuild vs numerous arbitrarily
> > defined index rebuilds). I don't think trading the independent
> > repack-ability of a toast table for a bit of performance with small
> > toasted values is a reasonable tradeoff for every user.
Not just small toast values, large ones can also be made faster as a follow-up.
Once you have a chunk offset array, you can start putting one large
chunk per page instead of four small ones.
And I am not claiming it is best for all corner cases, likke already
having an old bloated toast table wgich needs repacking. That one
should be repacked before enabling direct toast. Once Direct TOAST is
enabled you can keep the bloat down.
> > > ## In conclusion:
> > >
> > > I still think that these three goals
> > > - zero-downtime upgrade
> > > - less space used
> > > - faster performance
> > > are equally important and should be tackled together.
> > >
> > > As for your performance concerns, can you point me to use cases where
> > > you think the current oid4 can be faster?
> > > It does not have to be very detailed, just a general workload description helps.
> >
> > I'd consider huge toasted values as a case where index lookups can be
> > faster, because it automatically gains the benefits of performance
> > improvements in the index lookup path. The Direct Toast path needs to
> > manually build this feature.
Very performant is still slower than not doing it at all.
Currently DToast is roughly the same speed for huge toast values when
indexes are in memory, because the data page fetches dominate
It is significantly faster for cold caches.
But Direct TOAST structure allows it to be made even faster by adding
fored readahead and making use of direct io parallelism
> > And please test the performance difference between repacking a bloated
> > toast table vs repacking its main table with expensive-to-build
> > indexes (e.g. several gin on jsonb, pg_trgm with large text, HNSW,
> > etc.). I think the cost of fixing bloat in the toast table will be
> > much lower than repacking the main table+indexes with it.
I would rather make avoiding the need to repack a priority :)
There will always be ways to mess up your database.
But this makes me realise that I should only add the Direct TOAST
columns (and thus disable direct repack) if the corresponding table
option toast_flavour=direct is set so people who want to retain this
option can do so.
> > > I will run some tests to see if extra checks for direct toast and
> > > index predicate has a measurable effect in oid4 path.
> >
> > Note that PG currently has no builtin partial index definitions in its
> > catalogs, they're only present on user-controlled table definitions.
> > The suggested exclusion of "direct toast" values from the toast index
> > would be a first, and I'm not sure that's something that we want.
I have wanted it before :)
For splitting FUNCTION and PROCEDURE namespaces without needing to
move them to separate system tables.
The toast index is a special case used by a very specific path that
does not really need to care about the predicate as it already knows
weather toi use index or not fased on from which type of toast pointer
comes from.
And for user queries the system does not care if the queried table is
a system table or not.
That said, do you have any specific concerns about having partial
indexes in catalogs?
Many fancy features in catalogs are not really used *from the
catalogs* anyway - instead our code "just knows" they are there and
the catalogs only document that.
I have added a benchmark report as pdf here as it would be even less
readablke if converted to text :)
Note that the largest speedup of 129x there is not from direct toast
but from patching pg_vector to calculate vector dims directly from
varlena pointer. and some other as well are from teaching pg_vector to
use toast slice reads. I will make pull requests to pg_vector for
these soon.
Re: Direct TOAST v2, faster, smaller and no migration needed
От:
Hannu Krosing <hannuk@google.com>
Дата:
On Wed, Sep 30, 2026 at 4:56 AM Michael Paquier wrote: > > Yes, we've relied on the concept of TOAST tuple "identity" heavily for > 20-ish years. I will investigate an option to include more resiliency data, including chunk numbers, in the larger TOAST chunks. They probably would be redundant in single-chunk toast I will also investigate adding a back-pointer to the original tuple, which can be handy in some repacking scenarios. > You could introduce a new behavior based on tids as an opt-in, I > guess, leaving the default 4-bytes be, giving access to tid-based > access tables for newly-created TOAST tables. It was already optional and dynamic ALTER TABLE ... WITH (toast_flavour=direct) It is already implemented for both 4- and 8-byte-oid toast The latest discussion made me realise that I should also keep the table structure as the classic/plain toast with just three fields unless direct toast is requested so that the VACUUMing properties stay the same . The extra fields will only be added when you set the direct toast option, after that, direct vacuuming of toast will be disabled. -- Hannu
Re: Direct TOAST v2, faster, smaller and no migration needed
От:
Hannu Krosing <hannuk@google.com>
Дата:
Вложения:
From 105ac823c6c749d3cc586f4ab76464cde94ee5a6 Mon Sep 17 00:00:00 2001
From: Hannu Krosing
Date: Wed, 30 Sep 2026 17:57:53 +0000
Subject: [PATCH v12 00/10] Direct TOAST: Index-free out-of-line
varlena storage via physical TIDs
Hi hackers,
Please find attached v12 of the Direct TOAST patch series, rebased onto
current master (a36e2f7cd21), incorporating native interoperability with
64-bit TOAST value identifiers (toast_value_type = 'oid' / 'oid8'),
index-free self-pruning (LP_UNUSED / direct_toast_self_prune), vectored
multi-block detoasting, and deterministic regression tests and benchmarks
demonstrating Direct TOAST's advantages over both 32-bit oid and 64-bit
oid8 plain TOAST.
=== Overview & Architecture ===
Standard ("Plain") TOAST assigns a logical identifier (chunk_id) to each
out-of-line value and relies on a B-tree index on (chunk_id, chunk_seq) to
locate chunks. While 64-bit oid8 TOAST identifiers eliminate the global OID
wraparound and collision bottleneck, Plain TOAST still incurs:
1. B-tree index insertion, page splits, and WAL overhead on every out-of-line
write (and, for 64-bit oid8, 50% wider 24-byte aligned index tuples vs
16-byte oid index tuples).
2. B-tree root-to-leaf traversal buffer pins on every detoast read.
3. Two-phase vacuuming before dead TOAST heap line pointers (LP_DEAD) can
be recycled to LP_UNUSED, because index entries may still reference
them.
Direct TOAST (VARTAG_DIRECT, 20-byte struct varatt_direct payload, 22-byte
total on-disk pointer datum) eliminates the B-tree lookup and index maintenance
entirely by embedding the physical ItemPointerData (va_tid) of the root
TOAST tuple directly in the external varlena pointer.
When toast_default_flavour = 'plain' (the default) and toast_flavour is not
set to 'direct' on the parent table, newly created TOAST tables use the
traditional 3-column schema (chunk_id, chunk_seq, chunk_data) with a
non-partial primary key index on (chunk_id, chunk_seq).
When toast_default_flavour = 'direct' or when toast_flavour = 'direct' is set
on the parent table, TOAST tables use the 5-column Direct TOAST schema:
- chunk_id (oid or oid8, NULL for Direct TOAST tuples)
- chunk_seq (int4, 0-based sequential chunk index)
- chunk_data (bytea, NULL for pure interior tree nodes)
- chunk_tids (tid[], NULL for leaf chunks)
- chunk_tid_offsets (int8[], NULL for leaf and flat multi-chunk roots)
and a partial unique index:
CREATE UNIQUE INDEX ... ON pg_toast.pg_toast_ (chunk_id,
chunk_seq) WHERE chunk_id IS NOT NULL;
Because chunk_id is NULL for Direct TOAST tuples, the B-tree index is
completely bypassed during Direct TOAST writes, updates, and deletes, while
remaining available for Plain TOAST tuples in the same table. Actual INSERT
and UPDATE operations always follow the parent table's toast_flavour storage
parameter, and setting ALTER TABLE ... SET (toast_flavour = 'direct') on a
table with a 3-column TOAST table automatically upgrades its TOAST table
in-place to the 5-column Direct TOAST format.
=== Three-Tier Storage Layout ===
Depending on the size of the out-of-line value (total_chunks relative to
TOAST_MAX_CHUNK_SIZE), Direct TOAST automatically selects one of three
organizations:
1. Tier 1 — Single-Chunk (total_chunks == 1, <= ~2 KB):
va_tid points directly to the single TOAST tuple (chunk_id = NULL,
chunk_tids = NULL, chunk_tid_offsets = NULL). Reading requires 1 heap
fetch and 0 index fetches.
2. Tier 2 — Flat Multi-Chunk (2 <= total_chunks <= DIRECT_TOAST_TREE_THRESHOLD
[100], up to ~200 KB):
Leaf chunks 0 .. N-2 are written first (chunk_tids = NULL), followed by
root chunk N-1 which stores its own trailing chunk_data slice alongside
chunk_tids = [TID_0 .. TID_{N-2}] (chunk_tid_offsets = NULL). Uniform
chunk sizing allows O(1) offset calculation for substring slice reads.
3. Tier 3 — Hierarchical Tree (total_chunks > 100, up to 1 GB):
Leaf data chunks are written first, followed by interior routing nodes with
fanout up to DIRECT_TOAST_FANOUT (50) and maximum depth bounded by
DIRECT_TOAST_MAX_DEPTH (16). Each interior node stores chunk_data = NULL,
chunk_tids (tid[]), and chunk_tid_offsets (int8[] of count + 1
cumulative byte boundaries), enabling O(log_50 N) binary-search routing for
arbitrary byte-range slice reads.
=== Changes in v12 ===
1. Rebased onto master (a36e2f7cd21) with full oid / oid8 interoperability
and separated GUC vs reloption semantics:
- Integrates with upstream's toast_value_type ('oid' or 'oid8') storage
parameter alongside the toast_flavour ('plain' or 'direct') table
reloption and the toast_default_flavour ('plain' or 'direct') GUC.
- toast_default_flavour controls only whether new TOAST tables are created
in the traditional 3-column format or the 5-column Direct TOAST format
(keeping default catalog and regression table definitions unchanged from
master), whereas actual INSERT/UPDATE operations always use the table's
toast_flavour reloption.
- VACUUM FULL / CLUSTER / REPACK directly on a TOAST table checks the TOAST
table's column format (RelationGetNumberOfAttributes(OldHeap) >= 5).
- Fixed partial index predicate generation in create_toast_table() and
ensure_direct_toast() to inspect the TOAST table's actual chunk_id
attribute type (oid or oid8).
2. Index-free self-pruning (LP_UNUSED) and direct_toast_self_prune:
- In heap_page_prune_and_freeze() (pruneheap.c), dead TOAST tuples with
chunk_id IS NULL (heap_tuple_header_is_unindexed_toast()) cannot be
referenced by the partial index (WHERE chunk_id IS NOT NULL) and never
use HOT chains, allowing them to be pruned directly to LP_UNUSED in a
single pass without waiting for index vacuuming.
- Added the direct_toast_self_prune GUC and reloption (default on),
propagated from parent tables to their TOAST relations in
create_toast_table() and ATExecSetRelOptions().
- When deleting Direct TOAST chunks, candidate free space is recorded in the
TOAST relation's FSM and delete_count is incremented in the per-backend
DirectToastPruneState cache (keyed by TOAST relation OID via
toast_get_prune_state(), so state survives relcache invalidations and
-DRELCACHE_FORCE_RELEASE). During on-access pruning and
RelationGetBufferForTuple() on 5-column Direct TOAST tables, pages that
actually contain deleted Direct TOAST tuples
(toast_page_has_deleted_direct_tuple()) are pruned and recorded in the
FSM, and a bounded per-relation clock-hand probe reclaims space from
recently deleted pages before extending the TOAST relation, with zero
probe overhead on Plain TOAST tables or INSERT-only workloads.
3. Vectored detoasting & fast deletion:
- toast_fetch_datum_direct_slice_recursive() caches buffer pins per
tree depth (DirectToastLevelBufState), extracts chunk attributes in-place
via fastgetattr() without per-chunk TupleTableSlot allocations, and
prefetches contiguous multi-block leaf runs using StartReadBuffers() /
WaitReadBuffers() (up to io_combine_limit).
- toast_delete_datum_direct_recursive() replaces TupleTableSlot allocations
with heap_fetch() and fastgetattr(), and deletes Tier 2 leaf chunks
directly by TID via toast_direct_delete_tid() without fetching them first.
4. In-place 3-column TOAST upgrade & amcheck verification:
- ensure_direct_toast() / pg_ensure_direct_toast() (commit 0007) upgrades
3-column TOAST tables in-place to the 5-column Direct TOAST schema and
partial index without table rewrites (and runs automatically when
ALTER TABLE ... SET (toast_flavour = 'direct') is executed), preserving
readability of existing Plain TOAST pointers alongside new Direct TOAST
pointers.
- verify_heapam (contrib/amcheck, commit 0005) validates Direct TOAST
pointers (va_toastrelid, va_tid, size metadata) and recursively verifies
the Direct TOAST chunk graph (chunk_id IS NULL, chunk_seq >= 0,
chunk_tid_offsets monotonicity, child visibility, and exact byte size).
5. Four deterministic performance improvement regression tests in
direct_toast.sql:
- Performance Improvement Test 1 (Write Amplification, TOAST Index
Size & WAL Volume):
Compares plain (oid), plain (oid8), and direct on identical bulk inserts.
Verifies that the Direct TOAST partial index remains a single empty 8 KB
header page (pg_relation_size = 8192) while Plain oid and oid8 indexes
grow (idx_oid8_sz >= idx_oid_sz > 8192), and that Direct TOAST generates
fewer backend-local non-FPI WAL records and bytes (EXPLAIN (ANALYZE, WAL)).
- Performance Improvement Test 2 (Read & Slice Buffer Access
Efficiency Across All 3 Tiers):
Measured via pg_stat_get_xact_blocks_fetched /
pg_stat_get_xact_idx_blocks_fetched:
* Tier 1 (1.6 KB single-chunk) full read: Direct pins 1 TOAST heap block +
0 index blocks (vs Plain 1 heap + >= 1 index blocks).
* Tier 2 (22.4 KB flat multi-chunk) 500B prefix slice: Direct pins 2 TOAST
heap blocks (root + 1 leaf) and 0 index blocks.
* Tier 3 (320 KB tree DAG, 161 leaf chunks) 100B middle slice at offset
150 KB: Direct pins 3 TOAST heap blocks (root -> internal -> target leaf)
and 0 index blocks (53x fewer blocks than a full 161-chunk scan).
- Performance Improvement Test 3 (On-Access LP_UNUSED Self-Pruning
Without VACUUM):
With autovacuum_enabled = off and no VACUUM:
* Across 10 passes of per-row UPDATE churn, direct_toast_self_prune = on
maintains a TOAST table > 4x smaller than direct_toast_self_prune = off,
plain (oid), and plain (oid8), with a 1-page (8 KB) TOAST index.
* Across 6 passes of full-table single-transaction batch UPDATEs,
direct_toast_self_prune = on achieves zero steady-state growth
(sz_batch6 <= sz_batch1).
* Verifies that Plain TOAST tables (oid and oid8) do not incur 256-block
clock-hand probe amplification on extension.
- Performance Improvement Test 4 (Single-Pass VACUUM Without Index Scans):
After deleting all rows, VACUUM (INDEX_CLEANUP OFF) reclaims all dead
unindexed Direct TOAST tuples directly to LP_UNUSED during the first heap
pass and truncates the TOAST relation to 0 bytes, whereas plain (oid) and
plain (oid8) can only mark chunks LP_DEAD in the first pass and remain
> 500 KB without index cleanup and a second heap pass.
=== Benchmark Summary (Plain oid vs Plain oid8 vs Direct TOAST) ===
1. 30-Minute (1,800s) Parallel pgbench Multi-Column Insert Benchmark
(8 clients, 4 threads, shared_buffers = 16MB, synchronous_commit = off,
autovacuum = off; 2 KB inline pad + 8 x 100B STORAGE EXTERNAL columns =
8 TOAST chunks per row):
- plain (oid): 14,653.6 TPS (0.545 ms) | 26.38M rows (211.0M chunks) |
TOAST heap: 28 GB | TOAST index: 4,520 MB (16.1% of TOAST heap) |
1.32B TOAST index buffer hits (50.0 index pins/row)
- plain (oid8): 18,144.3 TPS (0.440 ms) | 32.66M rows (261.3M chunks) |
TOAST heap: 36 GB | TOAST index: 7,848 MB (21.8% of TOAST heap) |
604.8M TOAST index buffer hits (18.5 index pins/row)
- direct: 26,007.3 TPS (0.306 ms) | 46.81M rows (374.5M chunks) |
TOAST heap: 49 GB | TOAST index: 8,192 B (1 empty metapage) |
0 TOAST index buffer hits (0 index pins/row)
-> Direct TOAST sustains 1.77x higher insert TPS than plain (oid) and
1.43x higher TPS than plain (oid8), while eliminating 4.5–7.8 GB of
TOAST B-tree index bloat.
2. High-Churn UPDATE Self-Pruning (autovacuum = off, zero VACUUM calls):
- Single-client 20-pass full-table UPDATE churn (50 rows x 10 KB, 1,000
updates): direct (self_prune = on) maintains 512 kB TOAST heap (64 pages,
1.00x bloat = zero bloat), whereas direct (self_prune = off), plain (oid),
and plain (oid8) bloat to 10 MB (1,313 pages, ~19.1x–19.4x bloat).
- 8-client concurrent pgbench UPDATE churn (500 rows x ~9.6 KB,
autovacuum = off):
* plain (oid): 5,085 TPS (1.573 ms), 213 MB TOAST size
* plain (oid8): 1,535 TPS (5.211 ms), 66 MB TOAST size
* direct (self_prune = on): 29,941 TPS (0.267 ms), 7.2 MB TOAST size
-> Direct TOAST is 5.89x faster than oid (19.5x faster than oid8) with a
29.5x smaller TOAST table.
3. Read & Slice Efficiency Across All 3 Tiers + pgvector MRL subvector Slicing:
- Single-client (10 iterations):
* Tier 1 (1.6 KB x 5,000 rows) full scan: Direct is 3.57x faster than oid
(70.37 ms vs 251.48 ms; 5,000 total TOAST pins vs 15,000).
* pgvector vec1536 (6.1 KB x 2,000 rows): Full detoast (vector_norm) is
1.62x faster (104.07 ms vs 168.22 ms); MRL prefix slice subvector(1..128)
is 2.33x faster (45.27 ms vs 105.54 ms; 4,000 TOAST pins vs 6,000).
* pgvector vec5376 (21.5 KB x 1,000 rows): Full detoast (vector_norm) is
1.25x faster (138.74 ms vs 173.55 ms); MRL prefix slice subvector(1..256)
is 2.04x faster (26.22 ms vs 53.50 ms; 2,000 TOAST pins vs 3,000);
slice-aware vector_dims(emb) is 129x faster than full detoast (1.34 ms,
0 TOAST pins).
* Tier 3 (320 KB Tree DAG x 100 rows) middle slice @150 KB: Direct is
1.53x faster (3.65 ms vs 5.57 ms; 300 heap pins + 0 index pins).
- 8-client concurrent pgbench point reads on vec5376:
* Full vector read: 64,189 TPS (+8.2% vs 59,333 TPS oid / 59,277 TPS oid8).
* MRL subvector(1..256) slice: 70,612 TPS (+4.3% vs 67,715 TPS oid, and
+19.0% vs Plain full read).
4. 10 x 1 GB (10 GB Total, STORAGE EXTERNAL) Bulk Insert & 3-Level Cache Reads
(shared_buffers = 16GB, ~500,000 leaf chunks per 1 GB datum):
- Bulk INSERT (10 x 1 GB):
* plain (oid): 83.550 s (119.7 MB/s), 107 MB TOAST index, 5.24M idx hits,
10,143.5 MiB WAL
* plain (oid8): 83.065 s (120.4 MB/s), 151 MB TOAST index, 5.21M idx hits,
10,208.0 MiB WAL
* direct: 75.225 s (132.9 MB/s), 8,192 B TOAST index, 0 idx hits,
9,912.6 MiB WAL (-10.0% wall time, +11.0% throughput, -231 to
-295 MiB WAL)
- Level 1 Read (Hot shared_buffers + Hot OS page cache):
* 36.952 s (270.6 MB/s) for direct vs 38.502 s (oid) and 38.581 s (oid8).
Subtracting the fixed ~33.2 s UTF-8 length() character-counting CPU
overhead across 10B bytes, pure in-memory detoasting takes ~3.75 s
(2.67 GB/s) vs ~5.30 s (1.89 GB/s) — a 1.41x pure detoasting speedup.
- Level 2 Read (Cold shared_buffers + Hot OS page cache, 100% mincore):
* 45.747 s (218.6 MB/s) for direct vs 48.518 s (oid) and 48.677 s (oid8)
(-5.7% to -6.0% wall time). Vectored multi-block lookahead via
StartReadBuffers() issues 12.4x fewer preadv syscalls (102,396 vs
1,266,336 / 1,274,397, ~100 KB/op) and reduces pg_stat_io read I/O time
by 1.43–1.58 s (-12.9%).
- Level 3 Read (Cold shared_buffers + Cold OS page cache via
POSIX_FADV_DONTNEED, 0% mincore):
* 66.844 s (149.6 MB/s) for direct vs 68.898 s (oid) and 68.742 s (oid8)
(1.90–2.05 s faster end-to-end, 12.4x fewer preadv syscalls).
=== Patch Series Structure ===
0001: Refactor detoasting and decompression pipeline to unify full
and slice operations
0002: Add Direct TOAST catalog, GUC, and reloptions infrastructure
0003: Implement Direct TOAST core storage reading and writing
0004: Support Direct TOAST in logical decoding, replication, and online REPACK
0005: Add amcheck verification for Direct TOAST tuples
0006: Add documentation for Direct TOAST
0007: Add pg_ensure_direct_toast for in-place legacy TOAST table upgrade
0008: Add backend TOAST architecture documentation and clean up detoast access
0009: Prune dead unindexed TOAST tuples directly to LP_UNUSED
0010: Add direct_toast_self_prune, vectored detoasting, and
performance improvement tests
Hannu Krosing (10):
Refactor detoasting and decompression pipeline to unify full and slice
operations
Add Direct TOAST catalog, GUC, and reloptions infrastructure
Implement Direct TOAST core storage reading and writing
Support Direct TOAST in logical decoding, replication, and online
REPACK
Add amcheck verification for Direct TOAST tuples
Add documentation for Direct TOAST
Add pg_ensure_direct_toast for in-place legacy TOAST table upgrade
Add backend TOAST architecture documentation and clean up detoast
access
Prune dead unindexed TOAST tuples directly to LP_UNUSED
Add direct_toast_self_prune, vectored detoasting, and performance
improvement tests
contrib/amcheck/expected/check_heap.out | 29 +
contrib/amcheck/sql/check_heap.sql | 19 +
contrib/amcheck/verify_heapam.c | 302 +++++-
doc/src/sgml/config.sgml | 42 +
doc/src/sgml/ref/create_table.sgml | 40 +
doc/src/sgml/storage.sgml | 155 ++-
src/backend/access/common/README.toast | 124 +++
src/backend/access/common/detoast.c | 920 +++++++++++++----
src/backend/access/common/reloptions.c | 30 +
src/backend/access/common/toast_compression.c | 133 ++-
src/backend/access/common/toast_internals.c | 461 ++++++++-
src/backend/access/heap/hio.c | 113 +++
src/backend/access/heap/pruneheap.c | 86 +-
src/backend/access/table/toast_helper.c | 6 +-
src/backend/catalog/toasting.c | 287 +++++-
src/backend/commands/repack.c | 20 +-
src/backend/commands/tablecmds.c | 34 +
src/backend/replication/logical/decode.c | 7 +-
src/backend/replication/logical/proto.c | 2 +-
.../replication/logical/reorderbuffer.c | 210 +++-
src/backend/replication/pgoutput/pgoutput.c | 4 +-
src/backend/replication/pgrepack/pgrepack.c | 2 +-
src/backend/utils/adt/arrayfuncs.c | 6 +
src/backend/utils/fmgr/README | 4 +-
src/backend/utils/misc/guc_parameters.dat | 13 +
src/backend/utils/misc/guc_tables.c | 7 +
src/backend/utils/misc/postgresql.conf.sample | 2 +
src/include/access/detoast.h | 11 +
src/include/access/toast_internals.h | 51 +
src/include/catalog/pg_proc.dat | 5 +
src/include/catalog/toasting.h | 1 +
src/include/utils/rel.h | 15 +
src/include/varatt.h | 69 +-
src/test/modules/injection_points/Makefile | 1 +
.../expected/repack_direct_toast.out | 276 +++++
src/test/modules/injection_points/meson.build | 1 +
.../specs/repack_direct_toast.spec | 225 +++++
src/test/regress/expected/direct_toast.out | 1066 ++++++++++++++++++++
src/test/regress/parallel_schedule | 2 +-
src/test/regress/sql/direct_toast.sql | 914 +++++++++++++++++
40 files changed, 5324 insertions(+), 371 deletions(-)
create mode 100644 src/backend/access/common/README.toast
create mode 100644
src/test/modules/injection_points/expected/repack_direct_toast.out
create mode 100644
src/test/modules/injection_points/specs/repack_direct_toast.spec
create mode 100644 src/test/regress/expected/direct_toast.out
create mode 100644 src/test/regress/sql/direct_toast.sql
--
2.56.0.rc1.315.gc6ed9934b7-goog
On Wed, Sep 30, 2026 at 11:29 AM Hannu Krosing wrote:
>
> On Wed, Sep 30, 2026 at 4:56 AM Michael Paquier wrote:
> >
> > Yes, we've relied on the concept of TOAST tuple "identity" heavily for
> > 20-ish years.
>
> I will investigate an option to include more resiliency data,
> including chunk numbers, in the larger TOAST chunks. They probably
> would be redundant in single-chunk toast
>
> I will also investigate adding a back-pointer to the original tuple,
> which can be handy in some repacking scenarios.
>
> > You could introduce a new behavior based on tids as an opt-in, I
> > guess, leaving the default 4-bytes be, giving access to tid-based
> > access tables for newly-created TOAST tables.
>
> It was already optional and dynamic ALTER TABLE ... WITH (toast_flavour=direct)
>
> It is already implemented for both 4- and 8-byte-oid toast
>
> The latest discussion made me realise that I should also keep the
> table structure as the classic/plain toast with just three fields
> unless direct toast is requested so that the VACUUMing properties stay
> the same .
>
> The extra fields will only be added when you set the direct toast
> option, after that, direct vacuuming of toast will be disabled.
>
> --
> Hannu
Re: Direct TOAST v2, faster, smaller and no migration needed
От:
Hannu Krosing <hannuk@google.com>
Дата:
Вложения:
[PATCH v13 00/10] Direct TOAST: Index-free out-of-line varlena storage
via physical TIDs
Rebased again
Hi hackers,
Please find attached v13 of the Direct TOAST patch series, rebased onto
current master (e5d25959cf8), incorporating native interoperability with
64-bit TOAST value identifiers (toast_value_type = 'oid' / 'oid8'),
index-free self-pruning (LP_UNUSED / direct_toast_self_prune), vectored
multi-block detoasting, and deterministic regression tests and benchmarks
demonstrating Direct TOAST's performance improvements over both 32-bit oid
and 64-bit oid8 plain TOAST.
=== Overview & Architecture ===
Standard ("Plain") TOAST assigns a logical identifier (chunk_id) to each
out-of-line value and relies on a B-tree index on (chunk_id, chunk_seq) to
locate chunks. While 64-bit oid8 TOAST identifiers eliminate the global OID
wraparound and collision bottleneck, Plain TOAST still incurs:
1. B-tree index insertion, page splits, and WAL overhead on every out-of-line
write (and, for 64-bit oid8, 50% wider 24-byte aligned index tuples vs
16-byte oid index tuples).
2. B-tree root-to-leaf traversal buffer pins on every detoast read.
3. Two-phase vacuuming before dead TOAST heap line pointers (LP_DEAD) can
be recycled to LP_UNUSED, because index entries may still reference
them.
Direct TOAST (VARTAG_DIRECT, 20-byte struct varatt_direct payload, 22-byte
total on-disk pointer datum) eliminates the B-tree lookup and index maintenance
entirely by embedding the physical ItemPointerData (va_tid) of the root
TOAST tuple directly in the external varlena pointer.
When toast_default_flavour = 'plain' (the default) and toast_flavour is not
set to 'direct' on the parent table, newly created TOAST tables use the
traditional 3-column schema (chunk_id, chunk_seq, chunk_data) with a
non-partial primary key index on (chunk_id, chunk_seq).
When toast_default_flavour = 'direct' or when toast_flavour = 'direct' is set
on the parent table, TOAST tables use the 5-column Direct TOAST schema:
- chunk_id (oid or oid8, NULL for Direct TOAST tuples)
- chunk_seq (int4, 0-based sequential chunk index)
- chunk_data (bytea, NULL for pure interior tree nodes)
- chunk_tids (tid[], NULL for leaf chunks)
- chunk_tid_offsets (int8[], NULL for leaf and flat multi-chunk roots)
and a partial unique index:
CREATE UNIQUE INDEX ... ON pg_toast.pg_toast_ (chunk_id,
chunk_seq) WHERE chunk_id IS NOT NULL;
Because chunk_id is NULL for Direct TOAST tuples, the B-tree index is
completely bypassed during Direct TOAST writes, updates, and deletes, while
remaining available for Plain TOAST tuples in the same table. Actual INSERT
and UPDATE operations always follow the parent table's toast_flavour storage
parameter, and setting ALTER TABLE ... SET (toast_flavour = 'direct') on a
table with a 3-column TOAST table automatically upgrades its TOAST table
in-place to the 5-column Direct TOAST format.
=== Three-Tier Storage Layout ===
Depending on the size of the out-of-line value (total_chunks relative to
TOAST_MAX_CHUNK_SIZE), Direct TOAST automatically selects one of three
organizations:
1. Tier 1 — Single-Chunk (total_chunks == 1, <= ~2 KB):
va_tid points directly to the single TOAST tuple (chunk_id = NULL,
chunk_tids = NULL, chunk_tid_offsets = NULL). Reading requires 1 heap
fetch and 0 index fetches.
2. Tier 2 — Flat Multi-Chunk (2 <= total_chunks <= DIRECT_TOAST_TREE_THRESHOLD
[100], up to ~200 KB):
Leaf chunks 0 .. N-2 are written first (chunk_tids = NULL), followed by
root chunk N-1 which stores its own trailing chunk_data slice alongside
chunk_tids = [TID_0 .. TID_{N-2}] (chunk_tid_offsets = NULL). Uniform
chunk sizing allows O(1) offset calculation for substring slice reads.
3. Tier 3 — Hierarchical Tree (total_chunks > 100, up to 1 GB):
Leaf data chunks are written first, followed by interior routing nodes with
fanout up to DIRECT_TOAST_FANOUT (50) and maximum depth bounded by
DIRECT_TOAST_MAX_DEPTH (16). Each interior node stores chunk_data = NULL,
chunk_tids (tid[]), and chunk_tid_offsets (int8[] of count + 1
cumulative byte boundaries), enabling O(log_50 N) binary-search routing for
arbitrary byte-range slice reads.
=== Changes in v13 ===
1. Rebased onto master (e5d25959cf8) with full oid / oid8 interoperability,
REPACK (CONCURRENTLY) prepare_concurrent_update() integration, and
separated GUC vs reloption semantics:
- Integrates with upstream's toast_value_type ('oid' or 'oid8') storage
parameter alongside the toast_flavour ('plain' or 'direct') table
reloption and the toast_default_flavour ('plain' or 'direct') GUC.
- toast_default_flavour controls only whether new TOAST tables are created
in the traditional 3-column format or the 5-column Direct TOAST format
(keeping default catalog and regression table definitions unchanged from
master), whereas actual INSERT/UPDATE operations always use the table's
toast_flavour reloption.
- VACUUM FULL / CLUSTER / REPACK directly on a TOAST table checks the TOAST
table's column format (RelationGetNumberOfAttributes(OldHeap) >= 5).
- Fixed partial index predicate generation in create_toast_table() and
ensure_direct_toast() to inspect the TOAST table's actual chunk_id
attribute type (oid or oid8).
2. Index-free self-pruning (LP_UNUSED) and direct_toast_self_prune:
- In heap_page_prune_and_freeze() (pruneheap.c), dead TOAST tuples with
chunk_id IS NULL (heap_tuple_header_is_unindexed_toast()) cannot be
referenced by the partial index (WHERE chunk_id IS NOT NULL) and never
use HOT chains, allowing them to be pruned directly to LP_UNUSED in a
single pass without waiting for index vacuuming.
- Added the direct_toast_self_prune GUC and reloption (default on),
propagated from parent tables to their TOAST relations in
create_toast_table() and ATExecSetRelOptions().
- When deleting Direct TOAST chunks, candidate free space is recorded in the
TOAST relation's FSM and delete_count is incremented in the per-backend
DirectToastPruneState cache (keyed by TOAST relation OID via
toast_get_prune_state(), so state survives relcache invalidations and
-DRELCACHE_FORCE_RELEASE). During on-access pruning and
RelationGetBufferForTuple() on 5-column Direct TOAST tables, pages that
actually contain deleted Direct TOAST tuples
(toast_page_has_deleted_direct_tuple()) are pruned and recorded in the
FSM, and a bounded per-relation clock-hand probe reclaims space from
recently deleted pages before extending the TOAST relation, with zero
probe overhead on Plain TOAST tables or INSERT-only workloads.
3. Vectored detoasting & fast deletion:
- toast_fetch_datum_direct_slice_recursive() caches buffer pins per
tree depth (DirectToastLevelBufState), extracts chunk attributes in-place
via fastgetattr() without per-chunk TupleTableSlot allocations, and
prefetches contiguous multi-block leaf runs using StartReadBuffers() /
WaitReadBuffers() (up to io_combine_limit).
- toast_delete_datum_direct_recursive() replaces TupleTableSlot allocations
with heap_fetch() and fastgetattr(), and deletes Tier 2 leaf chunks
directly by TID via toast_direct_delete_tid() without fetching them first.
4. In-place 3-column TOAST upgrade & amcheck verification:
- ensure_direct_toast() / pg_ensure_direct_toast() (commit 0007) upgrades
3-column TOAST tables in-place to the 5-column Direct TOAST schema and
partial index without table rewrites (and runs automatically when
ALTER TABLE ... SET (toast_flavour = 'direct') is executed), preserving
readability of existing Plain TOAST pointers alongside new Direct TOAST
pointers.
- verify_heapam (contrib/amcheck, commit 0005) validates Direct TOAST
pointers (va_toastrelid, va_tid, size metadata) and recursively verifies
the Direct TOAST chunk graph (chunk_id IS NULL, chunk_seq >= 0,
chunk_tid_offsets monotonicity, child visibility, and exact byte size).
5. Four deterministic performance improvement regression tests in
direct_toast.sql:
- Performance Improvement Test 1 (Write Amplification, TOAST Index
Size & WAL Volume):
Compares plain (oid), plain (oid8), and direct on identical bulk inserts.
Verifies that the Direct TOAST partial index remains a single empty 8 KB
header page (pg_relation_size = 8192) while Plain oid and oid8 indexes
grow (idx_oid8_sz >= idx_oid_sz > 8192), and that Direct TOAST generates
fewer backend-local non-FPI WAL records and bytes (EXPLAIN (ANALYZE, WAL)).
- Performance Improvement Test 2 (Read & Slice Buffer Access
Efficiency Across All 3 Tiers):
Measured via pg_stat_get_xact_blocks_fetched /
pg_stat_get_xact_idx_blocks_fetched:
* Tier 1 (1.6 KB single-chunk) full read: Direct pins 1 TOAST heap block +
0 index blocks (vs Plain 1 heap + >= 1 index blocks).
* Tier 2 (22.4 KB flat multi-chunk) 500B prefix slice: Direct pins 2 TOAST
heap blocks (root + 1 leaf) and 0 index blocks.
* Tier 3 (320 KB tree DAG, 161 leaf chunks) 100B middle slice at offset
150 KB: Direct pins 3 TOAST heap blocks (root -> internal -> target leaf)
and 0 index blocks (53x fewer blocks than a full 161-chunk scan).
- Performance Improvement Test 3 (On-Access LP_UNUSED Self-Pruning
Without VACUUM):
With autovacuum_enabled = off and no VACUUM:
* Across 10 passes of per-row UPDATE churn, direct_toast_self_prune = on
maintains a TOAST table > 4x smaller than direct_toast_self_prune = off,
plain (oid), and plain (oid8), with a 1-page (8 KB) TOAST index.
* Across 6 passes of full-table single-transaction batch UPDATEs,
direct_toast_self_prune = on achieves zero steady-state growth
(sz_batch6 <= sz_batch1).
* Verifies that Plain TOAST tables (oid and oid8) do not incur 256-block
clock-hand probe amplification on extension.
- Performance Improvement Test 4 (Single-Pass VACUUM Without Index Scans):
After deleting all rows, VACUUM (INDEX_CLEANUP OFF) reclaims all dead
unindexed Direct TOAST tuples directly to LP_UNUSED during the first heap
pass and truncates the TOAST relation to 0 bytes, whereas plain (oid) and
plain (oid8) can only mark chunks LP_DEAD in the first pass and remain
> 500 KB without index cleanup and a second heap pass.
=== Benchmark Summary (Plain oid vs Plain oid8 vs Direct TOAST) ===
1. 30-Minute (1,800s) Parallel pgbench Multi-Column Insert Benchmark
(8 clients, 4 threads, shared_buffers = 16MB, synchronous_commit = off,
autovacuum = off; 2 KB inline pad + 8 x 100B STORAGE EXTERNAL columns =
8 TOAST chunks per row):
- plain (oid): 14,653.6 TPS (0.545 ms) | 26.38M rows (211.0M chunks) |
TOAST heap: 28 GB | TOAST index: 4,520 MB (16.1% of TOAST heap) |
1.32B TOAST index buffer hits (50.0 index pins/row)
- plain (oid8): 18,144.3 TPS (0.440 ms) | 32.66M rows (261.3M chunks) |
TOAST heap: 36 GB | TOAST index: 7,848 MB (21.8% of TOAST heap) |
604.8M TOAST index buffer hits (18.5 index pins/row)
- direct: 26,007.3 TPS (0.306 ms) | 46.81M rows (374.5M chunks) |
TOAST heap: 49 GB | TOAST index: 8,192 B (1 empty metapage) |
0 TOAST index buffer hits (0 index pins/row)
-> Direct TOAST sustains 1.77x higher insert TPS than plain (oid) and
1.43x higher TPS than plain (oid8), while eliminating 4.5–7.8 GB of
TOAST B-tree index bloat.
2. High-Churn UPDATE Self-Pruning (autovacuum = off, zero VACUUM calls):
- Single-client 20-pass full-table UPDATE churn (50 rows x 10 KB, 1,000
updates): direct (self_prune = on) maintains 512 kB TOAST heap (64 pages,
1.00x bloat = zero bloat), whereas direct (self_prune = off), plain (oid),
and plain (oid8) bloat to 10 MB (1,313 pages, ~19.1x–19.4x bloat).
- 8-client concurrent pgbench UPDATE churn (500 rows x ~9.6 KB,
autovacuum = off):
* plain (oid): 5,085 TPS (1.573 ms), 213 MB TOAST size
* plain (oid8): 1,535 TPS (5.211 ms), 66 MB TOAST size
* direct (self_prune = on): 29,941 TPS (0.267 ms), 7.2 MB TOAST size
-> Direct TOAST is 5.89x faster than oid (19.5x faster than oid8) with a
29.5x smaller TOAST table.
3. Read & Slice Efficiency Across All 3 Tiers + pgvector MRL subvector Slicing:
- Single-client (10 iterations):
* Tier 1 (1.6 KB x 5,000 rows) full scan: Direct is 3.57x faster than oid
(70.37 ms vs 251.48 ms; 5,000 total TOAST pins vs 15,000).
* pgvector vec1536 (6.1 KB x 2,000 rows): Full detoast (vector_norm) is
1.62x faster (104.07 ms vs 168.22 ms); MRL prefix slice subvector(1..128)
is 2.33x faster (45.27 ms vs 105.54 ms; 4,000 TOAST pins vs 6,000).
* pgvector vec5376 (21.5 KB x 1,000 rows): Full detoast (vector_norm) is
1.25x faster (138.74 ms vs 173.55 ms); MRL prefix slice subvector(1..256)
is 2.04x faster (26.22 ms vs 53.50 ms; 2,000 TOAST pins vs 3,000);
slice-aware vector_dims(emb) is 129x faster than full detoast (1.34 ms,
0 TOAST pins).
* Tier 3 (320 KB Tree DAG x 100 rows) middle slice @150 KB: Direct is
1.53x faster (3.65 ms vs 5.57 ms; 300 heap pins + 0 index pins).
- 8-client concurrent pgbench point reads on vec5376:
* Full vector read: 64,189 TPS (+8.2% vs 59,333 TPS oid / 59,277 TPS oid8).
* MRL subvector(1..256) slice: 70,612 TPS (+4.3% vs 67,715 TPS oid, and
+19.0% vs Plain full read).
4. 10 x 1 GB (10 GB Total, STORAGE EXTERNAL) Bulk Insert & 3-Level Cache Reads
(shared_buffers = 16GB, ~500,000 leaf chunks per 1 GB datum):
- Bulk INSERT (10 x 1 GB):
* plain (oid): 83.550 s (119.7 MB/s), 107 MB TOAST index, 5.24M idx hits,
10,143.5 MiB WAL
* plain (oid8): 83.065 s (120.4 MB/s), 151 MB TOAST index, 5.21M idx hits,
10,208.0 MiB WAL
* direct: 75.225 s (132.9 MB/s), 8,192 B TOAST index, 0 idx hits,
9,912.6 MiB WAL (-10.0% wall time, +11.0% throughput, -231 to
-295 MiB WAL)
- Level 1 Read (Hot shared_buffers + Hot OS page cache):
* 36.952 s (270.6 MB/s) for direct vs 38.502 s (oid) and 38.581 s (oid8).
Subtracting the fixed ~33.2 s UTF-8 length() character-counting CPU
overhead across 10B bytes, pure in-memory detoasting takes ~3.75 s
(2.67 GB/s) vs ~5.30 s (1.89 GB/s) — a 1.41x pure detoasting speedup.
- Level 2 Read (Cold shared_buffers + Hot OS page cache, 100% mincore):
* 45.747 s (218.6 MB/s) for direct vs 48.518 s (oid) and 48.677 s (oid8)
(-5.7% to -6.0% wall time). Vectored multi-block lookahead via
StartReadBuffers() issues 12.4x fewer preadv syscalls (102,396 vs
1,266,336 / 1,274,397, ~100 KB/op) and reduces pg_stat_io read I/O time
by 1.43–1.58 s (-12.9%).
- Level 3 Read (Cold shared_buffers + Cold OS page cache via
POSIX_FADV_DONTNEED, 0% mincore):
* 66.844 s (149.6 MB/s) for direct vs 68.898 s (oid) and 68.742 s (oid8)
(1.90–2.05 s faster end-to-end, 12.4x fewer preadv syscalls).
=== Patch Series Structure ===
0001: Refactor detoasting and decompression pipeline to unify full
and slice operations
0002: Add Direct TOAST catalog, GUC, and reloptions infrastructure
0003: Implement Direct TOAST core storage reading and writing
0004: Support Direct TOAST in logical decoding, replication, and online REPACK
0005: Add amcheck verification for Direct TOAST tuples
0006: Add documentation for Direct TOAST
0007: Add pg_ensure_direct_toast for in-place legacy TOAST table upgrade
0008: Add backend TOAST architecture documentation and clean up detoast access
0009: Prune dead unindexed TOAST tuples directly to LP_UNUSED
0010: Add direct_toast_self_prune, vectored detoasting, and
performance improvement tests
Hannu Krosing (10):
Refactor detoasting and decompression pipeline to unify full and slice
operations
Add Direct TOAST catalog, GUC, and reloptions infrastructure
Implement Direct TOAST core storage reading and writing
Support Direct TOAST in logical decoding, replication, and online
REPACK
Add amcheck verification for Direct TOAST tuples
Add documentation for Direct TOAST
Add pg_ensure_direct_toast for in-place legacy TOAST table upgrade
Add backend TOAST architecture documentation and clean up detoast
access
Prune dead unindexed TOAST tuples directly to LP_UNUSED
Add direct_toast_self_prune, vectored detoasting, and performance
improvement tests
contrib/amcheck/expected/check_heap.out | 29 +
contrib/amcheck/sql/check_heap.sql | 19 +
contrib/amcheck/verify_heapam.c | 302 ++++-
doc/src/sgml/config.sgml | 42 +
doc/src/sgml/ref/create_table.sgml | 40 +
doc/src/sgml/storage.sgml | 155 ++-
src/backend/access/common/README.toast | 124 ++
src/backend/access/common/detoast.c | 920 ++++++++++----
src/backend/access/common/reloptions.c | 30 +
src/backend/access/common/toast_compression.c | 133 +-
src/backend/access/common/toast_internals.c | 486 +++++++-
src/backend/access/heap/hio.c | 134 +++
src/backend/access/heap/pruneheap.c | 86 +-
src/backend/access/table/toast_helper.c | 6 +-
src/backend/catalog/toasting.c | 287 ++++-
src/backend/commands/repack.c | 20 +-
src/backend/commands/tablecmds.c | 34 +
src/backend/replication/logical/decode.c | 7 +-
src/backend/replication/logical/proto.c | 2 +-
.../replication/logical/reorderbuffer.c | 210 +++-
src/backend/replication/pgoutput/pgoutput.c | 4 +-
src/backend/replication/pgrepack/pgrepack.c | 2 +-
src/backend/utils/adt/arrayfuncs.c | 6 +
src/backend/utils/fmgr/README | 4 +-
src/backend/utils/misc/guc_parameters.dat | 13 +
src/backend/utils/misc/guc_tables.c | 7 +
src/backend/utils/misc/postgresql.conf.sample | 2 +
src/include/access/detoast.h | 11 +
src/include/access/toast_internals.h | 66 +
src/include/catalog/pg_proc.dat | 5 +
src/include/catalog/toasting.h | 1 +
src/include/utils/rel.h | 8 +
src/include/varatt.h | 69 +-
src/test/modules/injection_points/Makefile | 1 +
.../expected/repack_direct_toast.out | 276 +++++
src/test/modules/injection_points/meson.build | 1 +
.../specs/repack_direct_toast.spec | 225 ++++
src/test/regress/expected/direct_toast.out | 1067 +++++++++++++++++
src/test/regress/parallel_schedule | 2 +-
src/test/regress/sql/direct_toast.sql | 915 ++++++++++++++
40 files changed, 5380 insertions(+), 371 deletions(-)
create mode 100644 src/backend/access/common/README.toast
create mode 100644
src/test/modules/injection_points/expected/repack_direct_toast.out
create mode 100644
src/test/modules/injection_points/specs/repack_direct_toast.spec
create mode 100644 src/test/regress/expected/direct_toast.out
create mode 100644 src/test/regress/sql/direct_toast.sql
--
Hannu
Re: Direct TOAST v2, faster, smaller and no migration needed
От:
Matthias van de Meent <boekewurm+postgres@gmail.com>
Дата:
On Wed, 30 Sept 2026 at 11:15, Hannu Krosing wrote: > On Tue, Sep 29, 2026 at 2:19 PM Matthias van de Meent > > wrote: > > I think it's feasible for btree to further optimize its storage format > > of toast -like fixed-size nonnull column definitions, allowing for > > more entries per page. > > This will still not address the need to do index cleanups when pruning > deleted toast, which avoiding the index entirely does. As I described in my other mail, it does not avoid index maintenance unless you avoid indexes on the toast table entirely, which this proposal doesn't. > > > > > This is ensured by adding two new concepts to TOAST tables, even in > > > > > the existing TOAST 4-byte case: two new attributes and a partial > > > > > index. The existing attribute layer is moot when using one (4-byte > > > > > value) or the other (direct). This is a waste, and unlikely free. > > > > > The addition of a new partial index does not help much in that. > > > > > > > > It is not a *new* partial index, but the current PK is replaced with > > > > this. In case of online conversion, the current PK constraint is > > > > converted into this in-place. > > > > > > Don't you need a SHARE lock to build (replace) indexes? > > You need an exclusive lock for less than a millisecond to convert the > index in-place. Yes, but that still waits for other lockers to release, and newer lockers will conflict with this lock request and wait. A CREATE INDEX on a table will still cause writers to block when locking the table to add the new index definition. > > > > Finally, and the biggest elephant in the room here by far.. VACUUM > > > > FULL, CLUSTER and REPACK *have* to be forbidden, because on rewrite > > > > each command rewrites the tids in the parent. > > > > > > They are only forbidden directly on the toast table, they work fine > > > when run on main table > > > > But the independent repack-ability of toast tables is a very valuable > > feature. Main tables have indexes that may be very expensive to > > rebuild. Yes, CONCURRENTLY could help, but it'll still take a > > possibly huge amount of resources, in time, CPU, memory, disk, IO. > > Repacking the toast table separately solves bloat issues in the toast > > table, and does not require the main table to be rebuilt, avoiding the > > related resource consumptions of index builds etc. > > Good Point. This is an issue when the main table which is much larger > and more expensive index-wise than toast and toast is already messed up It's more an issue when the main table's indexes are expensive to build. It doesn't really depend on the size of the main table data; a toast table+index is (with high certainty) always cheaper to rebuild on its own than a toast table+index with its main table and its indexes. > (Though in this case I would expect the main problem to be the main > table, not toast) Why would it be? HOT updates on a table, with little data stored in the main table but a lot of columns pushed into TOAST (e.g. json(b) metadata fields) can definitely have a bloated TOAST table associated to a compact and well-organized main table. > If toast is not messed up, in-line pruning should keep the TOAST table > growth in check. Fragmentation can be a problem in any table with row churn that doesn't reap the benefits of guaranteed HOT updates. I don't see how any new direct TOAST system completely avoids this. > > > and they also result in a clustered order > > > synchronized with main table, which is not the case when running on > > > toast table directly with the current design > > > > Yes, repacking the toast table won't reorder the toast table to heap > > order, but in my humble opinion that's OK; just de-bloating the toast > > table and index is enough for some workloads. > > It is for some. > > And for even more workloads you do not need de-bloating at all, even > with current design. > > Direct Toast allows you to not get bloated in the first place because > of inline pruning and really cheap vacuum which needs to jsut look at > dirty pages and fully skip the index cleanup. Why would vacuum only need to look at dirty pages? Visibility (cleanup) horizons frequently outlast the current checkpoint, and can outlast even the buffer pool if/when replication is enabled, so only looking at dirtied pages is a very short-sighted method of cleanup. And I don't see why skipping index cleanup would be allowable in any world. > > > > That's a legal > > > > defensive set of commands because it is possible to reclaim bloat from > > > > TOAST relations directly, and I doubt that we'd *ever* want to drop > > > > this property, especially based on the benchmark claim of upthread. > > > > > > If you have a workload that updates toasted columns this results in > > > these being sprinkled all over the toast table, with random oids, so > > > even CLUSTER will not put them in the same order as main table. > > > > What do you mean by sprinkled all over and random OIDs? > > Toast IDs that are generated at about the same time will generally be > > closely related, and after CLUSTER these will be close together in the > > toast table, for both OID (very likely) and OID8 (practically > > guaranteed). > > > > They will definitely be in OID order, so what is the > > sprinkling randomness about? > > UPDATE will generate a new toasted value with newly allocated oid. If > some fields are updated late then they will not be close. What do you mean by late update? The SQL script you included didn't really show much other than that TOASTing values close in time produces close-in-value toast IDs, which is expected. And those close-in-value IDs are likely placed near eachother (and definitely placed near eachother after a CLUSTER of the toast table) > > > > This is why you want to run REPACK on the main table if you need to > > > > recover space AND also care about performance. > > > > In my tests autovacuum kept the direct toast table in shape more > > > > efficiently, most likely because it could skip the expensive index > > > > cleanup phase, so there was less bloat accumulating. > > > > > > How do you fit these claims together? > > > > > > 1. "zero-downtime / zero-migration switch to direct toast (and back)" > > > (from the start of the thread); > > > 2. No index cleanup phase > > > > > > If you can do a zero-migration change, old data will still have old > > > pointers, and those must be looked up through the index. > > > Once a table has an index, its vacuum MUST apply an index cleanup > > > phase, lest it contain any references to LP_DEAD line pointers still > > > present in the table. Note that LP_DEAD entries don't carry > > > information about which index(es) do or don't contain references to > > > that item, so you can't distinguish between included in and excluded > > > from the index -- all dead items must be processed. > > Latest few patch sets have includes a change to pruning which prunes > deleted direct toast chunks to LP_UNUSED directly > > So if you have been updating only direct toast pointers there will be > no dead tids collected. I categorically disagree with such a change. Index cleanup _must_ happen for non-HOT tuples when the table contains at least one non-summarizing index. > > > > > A > > > > > worst thing to me is that this seems to entirely disable their use due > > > > > to this in v2-0004, cluster_rel() or cluster.c: > > > > > + if (OldHeap->rd_rel->relkind == RELKIND_TOASTVALUE) > > > > > [..,] > > > > > + if (OldHeap->rd_att->natts >= 4 && > > > > > > > > > > The two new attributes are added *unconditionally*. > > > > > > > > Yes, but they are not used if you keep using only 4-byte OIDs. In that > > > > case they only appear in the catalog tables. > > > > > > That's not accurate; these columns will hold NULL values, which means > > > they'll bloat OID-toast tuples with a NULL bitmap, which will be one > > > MAXALIGN quantum in size in this table definition. > > There is always space for one byte of null bitmap after the 23-byte > tuple headers, so up to 8 attributes can have their null bitmap for > free. > > AND even now the three user attributes are not declared NOT NULL Correct, but this new scheme would change these into nullable attributes, requiring much more effort from every system to make sure they're accessing the right tuple data. > > > No, we don't recheck the valueid in the heaptuple. However, we do > > > check that the chunk counter matches the expected values, and that's > > > something that won't be possible in the direct toast design -- there > > > is nothing in the toast pointer nor the toast tuple that links it to > > > its own identity, especially not outside the scope of MVCC snapshots. > > Do you think it os a valuable property to have ? Yes. We have an active problem with SnapshotAny-scans in DDL that detoast recently-dead tuples' removed TOAST pointers, and the checks that we do have in place actively protect against real corruptions. It's bad we're hitting ERROR paths here, but it's much better than the alternative. > > > > > give the option for new tables to choose this method > > > > > (for the reasons listed in the last two paragraphs, I guess no anyway, > > > > > but that's what I would recommend if following up). > > > > > > > > The main reason you may want to REPACK *only* the toast table is that > > > > it currently behaves badly, partly because of expensive toast index > > > > cleanups. > > > > > > > > If you want performance back, you want to REPACK the main table, which > > > > fixes the random placement of toasted field problem. > > > > > > It is very feasible for the main table to be packed normally, whilst > > > the toast table becomes very bloated; this happens frequently when > > > large toasted columns get updated every once in a while with vacuum > > > and/or page pruning running just frequently enough to allow the main > > > table's tuple to fit back on the same page. REPACKing the main table > > > requires more locks and possibly much more time than just repacking > > > the toast table (one btree index rebuild vs numerous arbitrarily > > > defined index rebuilds). I don't think trading the independent > > > repack-ability of a toast table for a bit of performance with small > > > toasted values is a reasonable tradeoff for every user. > > Not just small toast values, large ones can also be made faster as a follow-up. > > Once you have a chunk offset array, you can start putting one large > chunk per page instead of four small ones. > > And I am not claiming it is best for all corner cases, likke already > having an old bloated toast table wgich needs repacking. That one > should be repacked before enabling direct toast. Once Direct TOAST is > enabled you can keep the bloat down. How do you do that? Direct toast pins the location of a toasted value into a specific physical page, you can't move it. If there's a churn in toasted values that temporarily can't be removed, and the newest (and surviving) value is located on the final page of the toast relation, how would you de-bloat that toast table? > > > > ## In conclusion: > > > > > > > > I still think that these three goals > > > > - zero-downtime upgrade > > > > - less space used > > > > - faster performance > > > > are equally important and should be tackled together. > > > > > > > > As for your performance concerns, can you point me to use cases where > > > > you think the current oid4 can be faster? > > > > It does not have to be very detailed, just a general workload description helps. > > > > > > I'd consider huge toasted values as a case where index lookups can be > > > faster, because it automatically gains the benefits of performance > > > improvements in the index lookup path. The Direct Toast path needs to > > > manually build this feature. > > Very performant is still slower than not doing it at all. True. But in this case we do need (a way to handle large column values). And given the page size limit, we'll have to cut up large values one way or another. And given that cutting up values, we'll probably want to avoid fragmenting the table. > Currently DToast is roughly the same speed for huge toast values when > indexes are in memory, because the data page fetches dominate > It is significantly faster for cold caches. > > But Direct TOAST structure allows it to be made even faster by adding > fored readahead and making use of direct io parallelism Which part of indexing won't allow that same optimization to be applied? Direct toast seems to be not dissimilar from a specialized inlined index; and these should allow similar features to be applied. The time spent optimizing the toast system for its own bespoke solution might better be spent on making the index path work better for TOAST. > > > And please test the performance difference between repacking a bloated > > > toast table vs repacking its main table with expensive-to-build > > > indexes (e.g. several gin on jsonb, pg_trgm with large text, HNSW, > > > etc.). I think the cost of fixing bloat in the toast table will be > > > much lower than repacking the main table+indexes with it. > > I would rather make avoiding the need to repack a priority :) > > There will always be ways to mess up your database. Yes, but I'd like to avoid raising the minimum cost of cleaning up messes that have already been made. I believe there is no reason that's good enough to require a strong coupling between toast and main table repacking. You may be able to get around this coupling by storing the TID + a "generation" ID, where repacking the toast table causes new generation IDs to be produced, and old generations are looked up in an index by [generation id, old head TID -> head TID], or even rewriting the chunks into the index as [generation_id, old TID, chunk_id -> chunk tid]. You'd keep most of the performance of direct toast in the common case (values created after table created & after last repack) without throwing out independent repackability. Note that TOAST tables can be the largest part of a table's total storage cost, or secondary only after the main table's indexes. Rebuilding it independently is exceedingly likely to be worth the effort, vs not cleaning up. > But this makes me realise that I should only add the Direct TOAST > columns (and thus disable direct repack) if the corresponding table > option toast_flavour=direct is set so people who want to retain this > option can do so. Except that you can't disable the direct toast -enabled "never repack again" poison once it's there, and I think that that is not an acceptable tradeoff. > That said, do you have any specific concerns about having partial > indexes in catalogs? They require relatively complicated allocations and handling in critical paths, so I like to avoid them whenever I can. We can make it work, for sure, but I'm not sure it's worth it for toast; especially given that expressions aren't exactly cheap to store in memory. FYI, there is an ongoing thread over at [0] discussing partial indexes in catalogs for other purposes. Kind regards, Matthias van de Meent Databricks (https://www.databricks.com) [0] https://www.postgresql.org/message-id/179089136170.117434.3768797469846977966%40gmail.com
Re: Direct TOAST v2, faster, smaller and no migration needed
On Mon, Oct 5, 2026 at 3:18 PM Matthias van de Meent wrote: > > On Wed, 30 Sept 2026 at 11:15, Hannu Krosing wrote: > > On Tue, Sep 29, 2026 at 2:19 PM Matthias van de Meent > > > wrote: > > > I think it's feasible for btree to further optimize its storage format > > > of toast -like fixed-size nonnull column definitions, allowing for > > > more entries per page. > > > > This will still not address the need to do index cleanups when pruning > > deleted toast, which avoiding the index entirely does. > > As I described in my other mail, it does not avoid index maintenance > unless you avoid indexes on the toast table entirely, which this > proposal doesn't. It does avoid index maintenance if you do not *use* any "plain" toast If VACUUM only sees dead direct toast tuples it collects zero dead tuple tids, and it does not run the index cleanup in case it has collected no indead tuples. > > > > > > This is ensured by adding two new concepts to TOAST tables, even in > > > > > > the existing TOAST 4-byte case: two new attributes and a partial > > > > > > index. The existing attribute layer is moot when using one (4-byte > > > > > > value) or the other (direct). This is a waste, and unlikely free. > > > > > > The addition of a new partial index does not help much in that. > > > > > > > > > > It is not a *new* partial index, but the current PK is replaced with > > > > > this. In case of online conversion, the current PK constraint is > > > > > converted into this in-place. > > > > > > > > Don't you need a SHARE lock to build (replace) indexes? > > > > You need an exclusive lock for less than a millisecond to convert the > > index in-place. > > Yes, but that still waits for other lockers to release, and newer > lockers will conflict with this lock request and wait. A CREATE INDEX > on a table will still cause writers to block when locking the table to > add the new index definition. It does not do CREATE INDEX. It updates pg_index and pg_constraint dirtectly > > > > > Finally, and the biggest elephant in the room here by far.. VACUUM > > > > > FULL, CLUSTER and REPACK *have* to be forbidden, because on rewrite > > > > > each command rewrites the tids in the parent. > > > > > > > > They are only forbidden directly on the toast table, they work fine > > > > when run on main table > > > > > > But the independent repack-ability of toast tables is a very valuable > > > feature. Main tables have indexes that may be very expensive to > > > rebuild. Yes, CONCURRENTLY could help, but it'll still take a > > > possibly huge amount of resources, in time, CPU, memory, disk, IO. > > > Repacking the toast table separately solves bloat issues in the toast > > > table, and does not require the main table to be rebuilt, avoiding the > > > related resource consumptions of index builds etc. > > > > Good Point. This is an issue when the main table which is much larger > > and more expensive index-wise than toast and toast is already messed up > > It's more an issue when the main table's indexes are expensive to > build. It doesn't really depend on the size of the main table data; a > toast table+index is (with high certainty) always cheaper to rebuild > on its own than a toast table+index with its main table and its > indexes. But main table and Direct TOAST *without indexes* can be in many cases cheaper to rebuild than toast table with indexes. > > (Though in this case I would expect the main problem to be the main > > table, not toast) > > Why would it be? HOT updates on a table, with little data stored in > the main table but a lot of columns pushed into TOAST (e.g. json(b) > metadata fields) can definitely have a bloated TOAST table associated > to a compact and well-organized main table. Sure. But I'd expect Direct TOAST to be able to avoid most of that bloat via in-line pruning to UNUSED > > If toast is not messed up, in-line pruning should keep the TOAST table > > growth in check. > > Fragmentation can be a problem in any table with row churn that > doesn't reap the benefits of guaranteed HOT updates. I don't see how > any new direct TOAST system completely avoids this. Nothing *completely* avoids this, at leas not with DBA doing some amount of planning and tuning. > > > > and they also result in a clustered order > > > > synchronized with main table, which is not the case when running on > > > > toast table directly with the current design > > > > > > Yes, repacking the toast table won't reorder the toast table to heap > > > order, but in my humble opinion that's OK; just de-bloating the toast > > > table and index is enough for some workloads. > > > > It is for some. > > > > And for even more workloads you do not need de-bloating at all, even > > with current design. > > > > Direct Toast allows you to not get bloated in the first place because > > of inline pruning and really cheap vacuum which needs to jsut look at > > dirty pages and fully skip the index cleanup. > > Why would vacuum only need to look at dirty pages? Visibility > (cleanup) horizons frequently outlast the current checkpoint, and can > outlast even the buffer pool if/when replication is enabled, so only > looking at dirtied pages is a very short-sighted method of cleanup. Again, it's not absolute solution. I can always costruct a use case where the most sensible solution is to shut down your business for a few hours and run VACUUM FULL or CLUSTER > And I don't see why skipping index cleanup would be allowable in any world. We do skip index cleanup when we prune other HEAP_ONLY_TUPLES. It is allowable exactly because there are no index pointers to them. Same for Direct TOAST tuples > > > > > That's a legal > > > > > defensive set of commands because it is possible to reclaim bloat from > > > > > TOAST relations directly, and I doubt that we'd *ever* want to drop > > > > > this property, especially based on the benchmark claim of upthread. > > > > > > > > If you have a workload that updates toasted columns this results in > > > > these being sprinkled all over the toast table, with random oids, so > > > > even CLUSTER will not put them in the same order as main table. > > > > > > What do you mean by sprinkled all over and random OIDs? > > > Toast IDs that are generated at about the same time will generally be > > > closely related, and after CLUSTER these will be close together in the > > > toast table, for both OID (very likely) and OID8 (practically > > > guaranteed). > > > > > > They will definitely be in OID order, so what is the > > > sprinkling randomness about? > > > > UPDATE will generate a new toasted value with newly allocated oid. If > > some fields are updated late then they will not be close. > > What do you mean by late update? When say you have multiple toasted values and you initially only insert one and other coime later, or when there are workflows that keep updating some of the toasted columns. > The SQL script you included didn't > really show much other than that TOASTing values close in time > produces close-in-value toast IDs, which is expected. And those > close-in-value IDs are likely placed near eachother (and definitely > placed near eachother after a CLUSTER of the toast table) I can send you another script which you can then run for ~10 days (I did) to verify that thins DO get messed up > > > > > This is why you want to run REPACK on the main table if you need to > > > > > recover space AND also care about performance. > > > > > In my tests autovacuum kept the direct toast table in shape more > > > > > efficiently, most likely because it could skip the expensive index > > > > > cleanup phase, so there was less bloat accumulating. > > > > > > > > How do you fit these claims together? > > > > > > > > 1. "zero-downtime / zero-migration switch to direct toast (and back)" > > > > (from the start of the thread); > > > > 2. No index cleanup phase > > > > > > > > If you can do a zero-migration change, old data will still have old > > > > pointers, and those must be looked up through the index. > > > > Once a table has an index, its vacuum MUST apply an index cleanup > > > > phase, lest it contain any references to LP_DEAD line pointers still > > > > present in the table. Note that LP_DEAD entries don't carry > > > > information about which index(es) do or don't contain references to > > > > that item, so you can't distinguish between included in and excluded > > > > from the index -- all dead items must be processed. > > > > Latest few patch sets have includes a change to pruning which prunes > > deleted direct toast chunks to LP_UNUSED directly > > > > So if you have been updating only direct toast pointers there will be > > no dead tids collected. > > I categorically disagree with such a change. Index cleanup _must_ > happen for non-HOT tuples when the table contains at least one > non-summarizing index. Can you elaborate, whay do you think you need to perform index cleanup when the firs pass deleted no rows that had indexes pointing to them ? > > > > > > A > > > > > > worst thing to me is that this seems to entirely disable their use due > > > > > > to this in v2-0004, cluster_rel() or cluster.c: > > > > > > + if (OldHeap->rd_rel->relkind == RELKIND_TOASTVALUE) > > > > > > [..,] > > > > > > + if (OldHeap->rd_att->natts >= 4 && > > > > > > > > > > > > The two new attributes are added *unconditionally*. > > > > > > > > > > Yes, but they are not used if you keep using only 4-byte OIDs. In that > > > > > case they only appear in the catalog tables. > > > > > > > > That's not accurate; these columns will hold NULL values, which means > > > > they'll bloat OID-toast tuples with a NULL bitmap, which will be one > > > > MAXALIGN quantum in size in this table definition. > > > > There is always space for one byte of null bitmap after the 23-byte > > tuple headers, so up to 8 attributes can have their null bitmap for > > free. > > > > AND even now the three user attributes are not declared NOT NULL > > Correct, but this new scheme would change these into nullable > attributes, requiring much more effort from every system to make sure > they're accessing the right tuple data. Again, they ALREADY are nullable, "> > AND even now the three user attributes are NOT declared NOT NULL" Can you elaborate on "requiring much more effort from every system" - which systems do you have in mind ? > > > > No, we don't recheck the valueid in the heaptuple. However, we do > > > > check that the chunk counter matches the expected values, and that's > > > > something that won't be possible in the direct toast design -- there > > > > is nothing in the toast pointer nor the toast tuple that links it to > > > > its own identity, especially not outside the scope of MVCC snapshots. > > > > Do you think it os a valuable property to have ? > > Yes. We have an active problem with SnapshotAny-scans in DDL that > detoast recently-dead tuples' removed TOAST pointers, and the checks > that we do have in place actively protect against real corruptions. > It's bad we're hitting ERROR paths here, but it's much better than the > alternative. Can you point me to the places where this is done ? > > > > > > give the option for new tables to choose this method > > > > > > (for the reasons listed in the last two paragraphs, I guess no anyway, > > > > > > but that's what I would recommend if following up). > > > > > > > > > > The main reason you may want to REPACK *only* the toast table is that > > > > > it currently behaves badly, partly because of expensive toast index > > > > > cleanups. > > > > > > > > > > If you want performance back, you want to REPACK the main table, which > > > > > fixes the random placement of toasted field problem. > > > > > > > > It is very feasible for the main table to be packed normally, whilst > > > > the toast table becomes very bloated; this happens frequently when > > > > large toasted columns get updated every once in a while with vacuum > > > > and/or page pruning running just frequently enough to allow the main > > > > table's tuple to fit back on the same page. REPACKing the main table > > > > requires more locks and possibly much more time than just repacking > > > > the toast table (one btree index rebuild vs numerous arbitrarily > > > > defined index rebuilds). I don't think trading the independent > > > > repack-ability of a toast table for a bit of performance with small > > > > toasted values is a reasonable tradeoff for every user. > > > > Not just small toast values, large ones can also be made faster as a follow-up. > > > > Once you have a chunk offset array, you can start putting one large > > chunk per page instead of four small ones. > > > > And I am not claiming it is best for all corner cases, likke already > > having an old bloated toast table wgich needs repacking. That one > > should be repacked before enabling direct toast. Once Direct TOAST is > > enabled you can keep the bloat down. > > How do you do that? Direct toast pins the location of a toasted value > into a specific physical page, you can't move it. If there's a churn > in toasted values that temporarily can't be removed, and the newest > (and surviving) value is located on the final page of the toast > relation, how would you de-bloat that toast table? Basically the same way I have been doing on-line de-bloating since 2006 :) Find the main row pointing to that toasted value, then update the toasted value until it does not fit on that page and then it moves to a lower one. See the attachce python script for doing this on normal table, this can be easily adapted to Direct TOAST, especially if we start adding back-pinters to toast chunks I know that the orthodox PostgreSQL de-bloating in this case either lcoking everything and running VACUUM FULL or REPACK > > > > > ## In conclusion: > > > > > > > > > > I still think that these three goals > > > > > - zero-downtime upgrade > > > > > - less space used > > > > > - faster performance > > > > > are equally important and should be tackled together. > > > > > > > > > > As for your performance concerns, can you point me to use cases where > > > > > you think the current oid4 can be faster? > > > > > It does not have to be very detailed, just a general workload description helps. > > > > > > > > I'd consider huge toasted values as a case where index lookups can be > > > > faster, because it automatically gains the benefits of performance > > > > improvements in the index lookup path. The Direct Toast path needs to > > > > manually build this feature. > > > > Very performant is still slower than not doing it at all. > > True. But in this case we do need (a way to handle large > column values). And given the page size limit, we'll have to cut up > large values one way or another. And given that cutting up values, > we'll probably want to avoid fragmenting the table. We can come back to this discussion once these benefits of performance improvements in the index lookup path materialize. > > Currently DToast is roughly the same speed for huge toast values when > > indexes are in memory, because the data page fetches dominate > > It is significantly faster for cold caches. > > > > But Direct TOAST structure allows it to be made even faster by adding > > fored readahead and making use of direct io parallelism > > Which part of indexing won't allow that same optimization to be > applied? Direct toast seems to be not dissimilar from a specialized > inlined index; and these should allow similar features to be applied. > The time spent optimizing the toast system for its own bespoke > solution might better be spent on making the index path work better > for TOAST. You can't really avoid accessing the index for index lookup paths, which by default involve fetching, pinning and locking the index pages. You can not make that faster than not doing any of that. The Indexed toast is currently a few tens of percent slower even if everything is in shared buffers. > > > > And please test the performance difference between repacking a bloated > > > > toast table vs repacking its main table with expensive-to-build > > > > indexes (e.g. several gin on jsonb, pg_trgm with large text, HNSW, > > > > etc.). I think the cost of fixing bloat in the toast table will be > > > > much lower than repacking the main table+indexes with it. > > > > I would rather make avoiding the need to repack a priority :) > > > > There will always be ways to mess up your database. > > Yes, but I'd like to avoid raising the minimum cost of cleaning up > messes that have already been made. I believe there is no reason > that's good enough to require a strong coupling between toast and main > table repacking. There are a few proposals pfor bringing back the overflow pages from the 1976 Ingres design. That would really make the coupling tight. > You may be able to get around this coupling by storing the TID + a > "generation" ID, where repacking the toast table causes new generation > IDs to be produced, and old generations are looked up in an index by > [generation id, old head TID -> head TID], or even rewriting the > chunks into the index as [generation_id, old TID, chunk_id -> chunk > tid]. > You'd keep most of the performance of direct toast in the common case > (values created after table created & after last repack) without > throwing out independent repackability. I have been working on a separate proposal doing something similar for GENERATED ALWAYS AS *ROW* IDENTITY which mostly uses TID expanded to 64 bits as ROW id and only puts the "row id" into a partial index if the row has to move off the original page and hot chains stop working for lookup :) This is closely related to my work on enabling REPLICA IDENTITY ROWID, which uses tid as identity. > Note that TOAST tables can be the largest part of a table's total > storage cost, or secondary only after the main table's indexes. > Rebuilding it independently is exceedingly likely to be worth the > effort, vs not cleaning up. Yes, I have seen real cases of running out of toast oids wheremore than 8TB of a total 9TB table was toast+toast index. In my extreme test running 10 days of massive updates on small toasted columns the Toast INDEX became the largest part of storage cost in case of indexed toast. Direct TOAST did not bloat the main TOAST table much, and of course it did not have the toast index at all. > > But this makes me realise that I should only add the Direct TOAST > > columns (and thus disable direct repack) if the corresponding table > > option toast_flavour=direct is set so people who want to retain this > > option can do so. > > Except that you can't disable the direct toast -enabled "never repack > again" poison once it's there, and I think that that is not an > acceptable tradeoff. You can still repack, just you have to do it together with main table. > > That said, do you have any specific concerns about having partial > > indexes in catalogs? > > They require relatively complicated allocations and handling in > critical paths, so I like to avoid them whenever I can. We can make > it work, for sure, but I'm not sure it's worth it for toast; > especially given that expressions aren't exactly cheap to store in > memory. Using from low-level system functions is allowed to just not care. And user query already do the right thing anyway, because the always *do* base their actions on what is in system tables. > FYI, there is an ongoing thread over at [0] discussing partial indexes > in catalogs for other purposes. Thank, will definitely rtake a look. > Kind regards, > > Matthias van de Meent > Databricks (https://www.databricks.com) > > [0] https://www.postgresql.org/message-id/179089136170.117434.3768797469846977966%40gmail.com
Re: Direct TOAST v2, faster, smaller and no migration needed
От:
Hannu Krosing <hannuk@google.com>
Дата:
Вложения:
Rebased as needed! On Mon, Oct 5, 2026 at 5:37 PM Hannu Krosing wrote: > > On Mon, Oct 5, 2026 at 3:18 PM Matthias van de Meent > wrote: > > > > On Wed, 30 Sept 2026 at 11:15, Hannu Krosing wrote: > > > On Tue, Sep 29, 2026 at 2:19 PM Matthias van de Meent > > > > wrote: > > > > I think it's feasible for btree to further optimize its storage format > > > > of toast -like fixed-size nonnull column definitions, allowing for > > > > more entries per page. > > > > > > This will still not address the need to do index cleanups when pruning > > > deleted toast, which avoiding the index entirely does. > > > > As I described in my other mail, it does not avoid index maintenance > > unless you avoid indexes on the toast table entirely, which this > > proposal doesn't. > > It does avoid index maintenance if you do not *use* any "plain" toast > If VACUUM only sees dead direct toast tuples it collects zero dead > tuple tids, and it does not run the index cleanup in case it has > collected no indead tuples. > > > > > > > > This is ensured by adding two new concepts to TOAST tables, even in > > > > > > > the existing TOAST 4-byte case: two new attributes and a partial > > > > > > > index. The existing attribute layer is moot when using one (4-byte > > > > > > > value) or the other (direct). This is a waste, and unlikely free. > > > > > > > The addition of a new partial index does not help much in that. > > > > > > > > > > > > It is not a *new* partial index, but the current PK is replaced with > > > > > > this. In case of online conversion, the current PK constraint is > > > > > > converted into this in-place. > > > > > > > > > > Don't you need a SHARE lock to build (replace) indexes? > > > > > > You need an exclusive lock for less than a millisecond to convert the > > > index in-place. > > > > Yes, but that still waits for other lockers to release, and newer > > lockers will conflict with this lock request and wait. A CREATE INDEX > > on a table will still cause writers to block when locking the table to > > add the new index definition. > > It does not do CREATE INDEX. It updates pg_index and pg_constraint dirtectly > > > > > > > Finally, and the biggest elephant in the room here by far.. VACUUM > > > > > > FULL, CLUSTER and REPACK *have* to be forbidden, because on rewrite > > > > > > each command rewrites the tids in the parent. > > > > > > > > > > They are only forbidden directly on the toast table, they work fine > > > > > when run on main table > > > > > > > > But the independent repack-ability of toast tables is a very valuable > > > > feature. Main tables have indexes that may be very expensive to > > > > rebuild. Yes, CONCURRENTLY could help, but it'll still take a > > > > possibly huge amount of resources, in time, CPU, memory, disk, IO. > > > > Repacking the toast table separately solves bloat issues in the toast > > > > table, and does not require the main table to be rebuilt, avoiding the > > > > related resource consumptions of index builds etc. > > > > > > Good Point. This is an issue when the main table which is much larger > > > and more expensive index-wise than toast and toast is already messed up > > > > It's more an issue when the main table's indexes are expensive to > > build. It doesn't really depend on the size of the main table data; a > > toast table+index is (with high certainty) always cheaper to rebuild > > on its own than a toast table+index with its main table and its > > indexes. > > But main table and Direct TOAST *without indexes* can be in many cases > cheaper to rebuild than toast table with indexes. > > > > (Though in this case I would expect the main problem to be the main > > > table, not toast) > > > > Why would it be? HOT updates on a table, with little data stored in > > the main table but a lot of columns pushed into TOAST (e.g. json(b) > > metadata fields) can definitely have a bloated TOAST table associated > > to a compact and well-organized main table. > > Sure. But I'd expect Direct TOAST to be able to avoid most of that > bloat via in-line pruning to UNUSED > > > > If toast is not messed up, in-line pruning should keep the TOAST table > > > growth in check. > > > > Fragmentation can be a problem in any table with row churn that > > doesn't reap the benefits of guaranteed HOT updates. I don't see how > > any new direct TOAST system completely avoids this. > > Nothing *completely* avoids this, at leas not with DBA doing some > amount of planning and tuning. > > > > > > and they also result in a clustered order > > > > > synchronized with main table, which is not the case when running on > > > > > toast table directly with the current design > > > > > > > > Yes, repacking the toast table won't reorder the toast table to heap > > > > order, but in my humble opinion that's OK; just de-bloating the toast > > > > table and index is enough for some workloads. > > > > > > It is for some. > > > > > > And for even more workloads you do not need de-bloating at all, even > > > with current design. > > > > > > Direct Toast allows you to not get bloated in the first place because > > > of inline pruning and really cheap vacuum which needs to jsut look at > > > dirty pages and fully skip the index cleanup. > > > > Why would vacuum only need to look at dirty pages? Visibility > > (cleanup) horizons frequently outlast the current checkpoint, and can > > outlast even the buffer pool if/when replication is enabled, so only > > looking at dirtied pages is a very short-sighted method of cleanup. > > Again, it's not absolute solution. I can always costruct a use case > where the most sensible solution is to shut down your business for a > few hours and run VACUUM FULL or CLUSTER > > > And I don't see why skipping index cleanup would be allowable in any world. > > We do skip index cleanup when we prune other HEAP_ONLY_TUPLES. > > It is allowable exactly because there are no index pointers to them. > > Same for Direct TOAST tuples > > > > > > > That's a legal > > > > > > defensive set of commands because it is possible to reclaim bloat from > > > > > > TOAST relations directly, and I doubt that we'd *ever* want to drop > > > > > > this property, especially based on the benchmark claim of upthread. > > > > > > > > > > If you have a workload that updates toasted columns this results in > > > > > these being sprinkled all over the toast table, with random oids, so > > > > > even CLUSTER will not put them in the same order as main table. > > > > > > > > What do you mean by sprinkled all over and random OIDs? > > > > Toast IDs that are generated at about the same time will generally be > > > > closely related, and after CLUSTER these will be close together in the > > > > toast table, for both OID (very likely) and OID8 (practically > > > > guaranteed). > > > > > > > > They will definitely be in OID order, so what is the > > > > sprinkling randomness about? > > > > > > UPDATE will generate a new toasted value with newly allocated oid. If > > > some fields are updated late then they will not be close. > > > > What do you mean by late update? > > When say you have multiple toasted values and you initially only > insert one and other coime later, or when there are workflows that > keep updating some of the toasted columns. > > > The SQL script you included didn't > > really show much other than that TOASTing values close in time > > produces close-in-value toast IDs, which is expected. And those > > close-in-value IDs are likely placed near eachother (and definitely > > placed near eachother after a CLUSTER of the toast table) > > I can send you another script which you can then run for ~10 days (I > did) to verify that thins DO get messed up > > > > > > > This is why you want to run REPACK on the main table if you need to > > > > > > recover space AND also care about performance. > > > > > > In my tests autovacuum kept the direct toast table in shape more > > > > > > efficiently, most likely because it could skip the expensive index > > > > > > cleanup phase, so there was less bloat accumulating. > > > > > > > > > > How do you fit these claims together? > > > > > > > > > > 1. "zero-downtime / zero-migration switch to direct toast (and back)" > > > > > (from the start of the thread); > > > > > 2. No index cleanup phase > > > > > > > > > > If you can do a zero-migration change, old data will still have old > > > > > pointers, and those must be looked up through the index. > > > > > Once a table has an index, its vacuum MUST apply an index cleanup > > > > > phase, lest it contain any references to LP_DEAD line pointers still > > > > > present in the table. Note that LP_DEAD entries don't carry > > > > > information about which index(es) do or don't contain references to > > > > > that item, so you can't distinguish between included in and excluded > > > > > from the index -- all dead items must be processed. > > > > > > Latest few patch sets have includes a change to pruning which prunes > > > deleted direct toast chunks to LP_UNUSED directly > > > > > > So if you have been updating only direct toast pointers there will be > > > no dead tids collected. > > > > I categorically disagree with such a change. Index cleanup _must_ > > happen for non-HOT tuples when the table contains at least one > > non-summarizing index. > > Can you elaborate, whay do you think you need to perform index cleanup > when the firs pass deleted no rows that had indexes pointing to them ? > > > > > > > > A > > > > > > > worst thing to me is that this seems to entirely disable their use due > > > > > > > to this in v2-0004, cluster_rel() or cluster.c: > > > > > > > + if (OldHeap->rd_rel->relkind == RELKIND_TOASTVALUE) > > > > > > > [..,] > > > > > > > + if (OldHeap->rd_att->natts >= 4 && > > > > > > > > > > > > > > The two new attributes are added *unconditionally*. > > > > > > > > > > > > Yes, but they are not used if you keep using only 4-byte OIDs. In that > > > > > > case they only appear in the catalog tables. > > > > > > > > > > That's not accurate; these columns will hold NULL values, which means > > > > > they'll bloat OID-toast tuples with a NULL bitmap, which will be one > > > > > MAXALIGN quantum in size in this table definition. > > > > > > There is always space for one byte of null bitmap after the 23-byte > > > tuple headers, so up to 8 attributes can have their null bitmap for > > > free. > > > > > > AND even now the three user attributes are not declared NOT NULL > > > > Correct, but this new scheme would change these into nullable > > attributes, requiring much more effort from every system to make sure > > they're accessing the right tuple data. > > Again, they ALREADY are nullable, > > "> > AND even now the three user attributes are NOT declared NOT NULL" > > Can you elaborate on "requiring much more effort from every system" - > which systems do you have in mind ? > > > > > > No, we don't recheck the valueid in the heaptuple. However, we do > > > > > check that the chunk counter matches the expected values, and that's > > > > > something that won't be possible in the direct toast design -- there > > > > > is nothing in the toast pointer nor the toast tuple that links it to > > > > > its own identity, especially not outside the scope of MVCC snapshots. > > > > > > Do you think it os a valuable property to have ? > > > > Yes. We have an active problem with SnapshotAny-scans in DDL that > > detoast recently-dead tuples' removed TOAST pointers, and the checks > > that we do have in place actively protect against real corruptions. > > It's bad we're hitting ERROR paths here, but it's much better than the > > alternative. > > Can you point me to the places where this is done ? > > > > > > > > give the option for new tables to choose this method > > > > > > > (for the reasons listed in the last two paragraphs, I guess no anyway, > > > > > > > but that's what I would recommend if following up). > > > > > > > > > > > > The main reason you may want to REPACK *only* the toast table is that > > > > > > it currently behaves badly, partly because of expensive toast index > > > > > > cleanups. > > > > > > > > > > > > If you want performance back, you want to REPACK the main table, which > > > > > > fixes the random placement of toasted field problem. > > > > > > > > > > It is very feasible for the main table to be packed normally, whilst > > > > > the toast table becomes very bloated; this happens frequently when > > > > > large toasted columns get updated every once in a while with vacuum > > > > > and/or page pruning running just frequently enough to allow the main > > > > > table's tuple to fit back on the same page. REPACKing the main table > > > > > requires more locks and possibly much more time than just repacking > > > > > the toast table (one btree index rebuild vs numerous arbitrarily > > > > > defined index rebuilds). I don't think trading the independent > > > > > repack-ability of a toast table for a bit of performance with small > > > > > toasted values is a reasonable tradeoff for every user. > > > > > > Not just small toast values, large ones can also be made faster as a follow-up. > > > > > > Once you have a chunk offset array, you can start putting one large > > > chunk per page instead of four small ones. > > > > > > And I am not claiming it is best for all corner cases, likke already > > > having an old bloated toast table wgich needs repacking. That one > > > should be repacked before enabling direct toast. Once Direct TOAST is > > > enabled you can keep the bloat down. > > > > How do you do that? Direct toast pins the location of a toasted value > > into a specific physical page, you can't move it. If there's a churn > > in toasted values that temporarily can't be removed, and the newest > > (and surviving) value is located on the final page of the toast > > relation, how would you de-bloat that toast table? > > Basically the same way I have been doing on-line de-bloating since 2006 :) > > Find the main row pointing to that toasted value, then update the > toasted value until it does not fit on that page and then it moves to > a lower one. > > See the attachce python script for doing this on normal table, this > can be easily adapted to Direct TOAST, especially if we start adding > back-pinters to toast chunks > > I know that the orthodox PostgreSQL de-bloating in this case either > lcoking everything and running VACUUM FULL or REPACK > > > > > > > ## In conclusion: > > > > > > > > > > > > I still think that these three goals > > > > > > - zero-downtime upgrade > > > > > > - less space used > > > > > > - faster performance > > > > > > are equally important and should be tackled together. > > > > > > > > > > > > As for your performance concerns, can you point me to use cases where > > > > > > you think the current oid4 can be faster? > > > > > > It does not have to be very detailed, just a general workload description helps. > > > > > > > > > > I'd consider huge toasted values as a case where index lookups can be > > > > > faster, because it automatically gains the benefits of performance > > > > > improvements in the index lookup path. The Direct Toast path needs to > > > > > manually build this feature. > > > > > > Very performant is still slower than not doing it at all. > > > > True. But in this case we do need (a way to handle large > > column values). And given the page size limit, we'll have to cut up > > large values one way or another. And given that cutting up values, > > we'll probably want to avoid fragmenting the table. > > We can come back to this discussion once these benefits of performance > improvements in the index lookup path materialize. > > > > Currently DToast is roughly the same speed for huge toast values when > > > indexes are in memory, because the data page fetches dominate > > > It is significantly faster for cold caches. > > > > > > But Direct TOAST structure allows it to be made even faster by adding > > > fored readahead and making use of direct io parallelism > > > > Which part of indexing won't allow that same optimization to be > > applied? Direct toast seems to be not dissimilar from a specialized > > inlined index; and these should allow similar features to be applied. > > The time spent optimizing the toast system for its own bespoke > > solution might better be spent on making the index path work better > > for TOAST. > > You can't really avoid accessing the index for index lookup paths, > which by default involve fetching, pinning and locking the index > pages. You can not make that faster than not doing any of that. > > The Indexed toast is currently a few tens of percent slower even if > everything is in shared buffers. > > > > > > > And please test the performance difference between repacking a bloated > > > > > toast table vs repacking its main table with expensive-to-build > > > > > indexes (e.g. several gin on jsonb, pg_trgm with large text, HNSW, > > > > > etc.). I think the cost of fixing bloat in the toast table will be > > > > > much lower than repacking the main table+indexes with it. > > > > > > I would rather make avoiding the need to repack a priority :) > > > > > > There will always be ways to mess up your database. > > > > Yes, but I'd like to avoid raising the minimum cost of cleaning up > > messes that have already been made. I believe there is no reason > > that's good enough to require a strong coupling between toast and main > > table repacking. > > There are a few proposals pfor bringing back the overflow pages from > the 1976 Ingres design. That would really make the coupling tight. > > > You may be able to get around this coupling by storing the TID + a > > "generation" ID, where repacking the toast table causes new generation > > IDs to be produced, and old generations are looked up in an index by > > [generation id, old head TID -> head TID], or even rewriting the > > chunks into the index as [generation_id, old TID, chunk_id -> chunk > > tid]. > > You'd keep most of the performance of direct toast in the common case > > (values created after table created & after last repack) without > > throwing out independent repackability. > > I have been working on a separate proposal doing something similar for > GENERATED ALWAYS AS *ROW* IDENTITY which mostly uses TID expanded to > 64 bits as ROW id and only puts the "row id" into a partial index if > the row has to move off the original page and hot chains stop working > for lookup :) > > This is closely related to my work on enabling REPLICA IDENTITY ROWID, > which uses tid as identity. > > > Note that TOAST tables can be the largest part of a table's total > > storage cost, or secondary only after the main table's indexes. > > Rebuilding it independently is exceedingly likely to be worth the > > effort, vs not cleaning up. > > Yes, I have seen real cases of running out of toast oids wheremore > than 8TB of a total 9TB table was toast+toast index. > > In my extreme test running 10 days of massive updates on small toasted > columns the Toast INDEX became the largest part of storage cost in > case of indexed toast. > > Direct TOAST did not bloat the main TOAST table much, and of course it > did not have the toast index at all. > > > > But this makes me realise that I should only add the Direct TOAST > > > columns (and thus disable direct repack) if the corresponding table > > > option toast_flavour=direct is set so people who want to retain this > > > option can do so. > > > > Except that you can't disable the direct toast -enabled "never repack > > again" poison once it's there, and I think that that is not an > > acceptable tradeoff. > > You can still repack, just you have to do it together with main table. > > > > That said, do you have any specific concerns about having partial > > > indexes in catalogs? > > > > They require relatively complicated allocations and handling in > > critical paths, so I like to avoid them whenever I can. We can make > > it work, for sure, but I'm not sure it's worth it for toast; > > especially given that expressions aren't exactly cheap to store in > > memory. > > Using from low-level system functions is allowed to just not care. > > And user query already do the right thing anyway, because the always > *do* base their actions on what is in system tables. > > > FYI, there is an ongoing thread over at [0] discussing partial indexes > > in catalogs for other purposes. > > Thank, will definitely rtake a look. > > > > Kind regards, > > > > Matthias van de Meent > > Databricks (https://www.databricks.com) > > > > [0] https://www.postgresql.org/message-id/179089136170.117434.3768797469846977966%40gmail.com
Re: Direct TOAST v2, faster, smaller and no migration needed
От:
Hannu Krosing <hannuk@google.com>
Дата:
Вложения:
Hi hackers,
Here is version 15 of the Direct TOAST patch set, based on PostgreSQL master
(commit abf5fec634f).
Changes in v15
--------------
- Catalog & DDL Hygiene (`ensure_direct_toast` in `toasting.c`):
- Factored attribute tuple insertion into `toast_add_attribute_tuples()` with
`CatalogOpenIndexes()` / `CatalogCloseIndexes()` batching.
- Recorded `DEPENDENCY_NORMAL` (`RelationRelationId` -> `TypeRelationId`) for
newly added `chunk_tids` (`_tid`) and `chunk_tid_offsets` (`_int8`) columns,
and fired `InvokeObjectPostCreateHook` / `InvokeObjectPostAlterHook`.
- Canonicalized `indpred` via `make_ands_explicit()` before `nodeToString()`
when converting legacy TOAST indexes to partial indexes (`WHERE chunk_id IS
NOT NULL`), and recorded single-relation expression dependencies via
`recordDependencyOnSingleRelExpr()`.
- `VACUUM FULL` / `CLUSTER` Flavour Transition (`toast_internals.c`):
- Guarded `toast_preserve_valueid()` with
`!VARATT_IS_EXTERNAL_ONDISK(oldexternal)`
so rewriting a table after changing `toast_flavour` from `'direct'` to
`'plain'` allocates a fresh `va_valueid` instead of reading
`va_tid` bytes as
an OID.
- Self-Pruning Concurrency & FSM Throttling (`hio.c`, `pruneheap.c`,
`toast_internals.c`):
- Enabled cross-session self-pruning when other backends delete Direct TOAST
tuples (`has_direct_toast`) and staggered initial `prune_hand` by
`MyProcNumber * 16` to avoid lock convoying across concurrent writers.
- Added pre-lock `GlobalVisTestIsRemovableXid()` horizon check on
`last_delete_xid` and preserved `loop_saw_inprogress` across transaction
boundaries to prevent wasteful buffer lock scans on uncommitted deletes.
- Replaced `GetRecordedFreeSpace()` after `heap_page_prune_opt()` with direct
`PageGetHeapFreeSpace(probePage)` inspection so small-chunk pages (< 20%
reclaimed) are still reused immediately by the pruning backend,
while secondary
batch-pruned pages are recorded in the FSM.
- Updated `heap_page_prune_opt()` to record FSM updates when either the
reclaimed delta reaches `DIRECT_TOAST_FSM_UPDATE_THRESHOLD` (`BLCKSZ / 5`)
or total page free space crosses the 20% threshold upward.
- Deduplicated per-block `RecordPageWithFreeSpace()` calls during multi-chunk
`toast_delete_datum_direct()`.
- Temporary TOAST Table Vectored I/O (`detoast.c`):
- Clamped `StartReadBuffers()` batch size to `nblocks = 1` when
`RelationUsesLocalBuffers(toastrel)` is true.
1. Problem & Motivation
-----------------------
PostgreSQL's traditional TOAST mechanism stores out-of-line varlena attributes
in auxiliary tables using a 3-column format: (chunk_id, chunk_seq, chunk_data).
Every stored chunk is indexed in a unique B-Tree index on (chunk_id, chunk_seq).
While this design is straightforward, it incurs substantial write amplification,
index bloat, and read latency:
- Write Amplification: Every out-of-line chunk insertion generates both a heap
write and a B-Tree index write, along with associated WAL records for page
allocations and splits.
- Index Bloat: For tables with high UPDATE/DELETE churn on toasted columns, the
TOAST index grows rapidly and requires full two-pass VACUUM cleanup.
- Detoasting Overhead: Reading even a small 2KB out-of-line value requires an
index probe, buffer lock, and heap fetch.
- Random Slicing: Reading partial slices from large multi-megabyte attributes
requires scanning sequential index entries rather than jumping directly to
the relevant byte range.
2. Overview of Direct TOAST Architecture
----------------------------------------
Direct TOAST eliminates index lookups and index maintenance by storing direct
physical tuple identifiers (ItemPointerData / TID) directly in the external
pointer and within chunk metadata.
- On-Disk Pointer (struct varatt_direct, VARTAG_DIRECT = 19):
20 bytes payload (22 bytes on disk with 2-byte header):
int32 va_rawsize; /* Original uncompressed data size */
uint32 va_extinfo; /* External stored size and
compression method */
Oid va_toastrelid; /* RelID of TOAST relation */
ItemPointerData va_tid; /* Physical TID of root/terminal chunk */
sizeof(varatt_direct) is identical to 64-bit OID8 pointers
(varatt_external_oid8).
- 5-Column TOAST Table Schema:
(chunk_id OID|OID8, chunk_seq INT4, chunk_data BYTEA,
chunk_tids TID[], chunk_tid_offsets INT8[])
Configured with a partial unique index on (chunk_id, chunk_seq)
WHERE chunk_id IS NOT NULL. Direct TOAST chunks have chunk_id IS NULL and
are never indexed, eliminating index insertion overhead entirely.
- Three-Tier Storage Hierarchy:
a) Single-Chunk Fast Path (<= TOAST_MAX_CHUNK_SIZE, ~2KB):
Main tuple's va_tid points directly to the single chunk tuple.
Detoasting is a single buffer page fetch with 0 index scans and 0
TupleTableSlot allocations.
b) Flat Multi-Chunk (2 <= chunks <= 100, up to ~200KB):
Leaf chunks 0..N-2 store data with chunk_id = NULL. The terminal chunk N-1
stores the final data slice and a chunk_tids array referencing the earlier
chunks. va_tid points to chunk N-1. Detoasting reads chunks
directly by TID.
c) Hierarchical Tree / DAG (> 100 chunks, multi-MB/GB values):
Chunks form a balanced tree with fanout 50. Internal nodes store child
chunk_tids and chunk_tid_offsets (cumulative byte boundaries).
Partial slice
reads (detoast_attr_slice) perform binary search at each level and prune
subtrees outside the slice range, achieving O(log N) random-access slicing.
- Opportunistic Pruning directly to LP_UNUSED:
Because Direct TOAST tuples are unindexed, dead chunks do not have index
pointers. Opportunistic page pruning (heap_page_prune_and_freeze) and VACUUM
mark dead Direct TOAST chunks directly as LP_UNUSED rather than LP_DEAD,
reclaiming page space and line pointers immediately without waiting for an
index vacuum.
- Self-Pruning & Vectored I/O:
- direct_toast_self_prune (GUC and reloption, default on) opportunistically
probes and prunes candidate pages with deleted Direct TOAST tuples before
extending a TOAST table, keeping space bounded under churn.
- Vectored multi-block reading prefetches contiguous leaf chunks using
StartReadBuffers() / WaitReadBuffers() up to io_combine_limit.
- Backward Compatibility & In-Place Upgrades:
Existing tables can be upgraded in place without rewriting rows via:
ALTER TABLE my_table SET (toast_flavour = direct);
or superuser SQL function:
SELECT pg_ensure_direct_toast('my_table'::regclass);
Legacy 3-column tables are altered in-place with fast-default NULLs for the
new columns and their index is converted to partial (WHERE chunk_id
IS NOT NULL).
Existing Plain TOAST values remain readable while new writes produce
Direct TOAST.
3. Structure of the Patch Set (10 Patches)
------------------------------------------
- Patch 0001: Refactor detoasting and decompression pipeline to unify full
and slice operations (unifies detoast_attr/detoast_attr_slice).
- Patch 0002: Add Direct TOAST catalog, GUC, and reloptions infrastructure
(struct varatt_direct, VARTAG_DIRECT, toast_flavour reloption,
toast_default_flavour GUC, create_toast_table schema).
- Patch 0003: Implement Direct TOAST core storage reading and writing
(toast_save_datum_direct, toast_fetch_datum_direct, tree/flat
traversal, recursive deletion, regression test suite).
- Patch 0004: Support Direct TOAST in logical decoding, replication, and
online REPACK (reorderbuffer TID keying, logicalrep protocol,
repack_direct_toast isolation test).
- Patch 0005: Add amcheck verification for Direct TOAST tuples (verify_heapam
validates direct pointers, TID ranges, DAG offset monotonicity).
- Patch 0006: Add documentation for Direct TOAST (SGML storage, config, and
create_table references).
- Patch 0007: Add pg_ensure_direct_toast for in-place legacy TOAST table upgrade
(in-place catalog and index upgrade).
- Patch 0008: Add backend TOAST architecture documentation and clean up detoast
access (src/backend/access/common/README.toast).
- Patch 0009: Prune dead unindexed TOAST tuples directly to LP_UNUSED
(pruneheap.c special-casing for unindexed TOAST chunks).
- Patch 0010: Add direct_toast_self_prune, vectored detoasting, and performance
improvement tests (self-pruning GUC/reloption, StartReadBuffers,
benchmark tests in direct_toast.sql).
4. Testing & Verification
-------------------------
The patch set was compiled and tested with:
CFLAGS="-O2 -ggdb -fsanitize=alignment,undefined -fno-sanitize-recover=all"
CPPFLAGS="-DRELCACHE_FORCE_RELEASE
-DENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS"
--enable-cassert --enable-injection-points --enable-tap-tests
Verification results:
- Core regression suite: all 240 tests passed (including direct_toast).
- contrib/amcheck: all 4 regress tests and all 6 TAP tests (298/298
subtests) passed.
- src/test/modules/injection_points: all 4 regress tests and all 18 isolation
tests (including repack_direct_toast) passed.
- Server log inspection: verified zero cache reference leaks, buffer refcount
leaks, or lock leaks.
The series is also available on GitHub at:
https://github.com/postsql/postgres/tree/direct-toast-submission
Feedback and reviews are welcome!
Hannu Krosing (10):
Refactor detoasting and decompression pipeline to unify full and slice
operations
Add Direct TOAST catalog, GUC, and reloptions infrastructure
Implement Direct TOAST core storage reading and writing
Support Direct TOAST in logical decoding, replication, and online
REPACK
Add amcheck verification for Direct TOAST tuples
Add documentation for Direct TOAST
Add pg_ensure_direct_toast for in-place legacy TOAST table upgrade
Add backend TOAST architecture documentation and clean up detoast
access
Prune dead unindexed TOAST tuples directly to LP_UNUSED
Add direct_toast_self_prune, vectored detoasting, and performance
improvement tests
contrib/amcheck/expected/check_heap.out | 29 +
contrib/amcheck/sql/check_heap.sql | 19 +
contrib/amcheck/verify_heapam.c | 302 ++++-
doc/src/sgml/config.sgml | 42 +
doc/src/sgml/ref/create_table.sgml | 40 +
doc/src/sgml/storage.sgml | 155 ++-
src/backend/access/common/README.toast | 124 ++
src/backend/access/common/detoast.c | 925 +++++++++----
src/backend/access/common/reloptions.c | 30 +
src/backend/access/common/toast_compression.c | 133 +-
src/backend/access/common/toast_internals.c | 520 +++++++-
src/backend/access/heap/hio.c | 186 +++
src/backend/access/heap/pruneheap.c | 100 +-
src/backend/access/table/toast_helper.c | 6 +-
src/backend/catalog/toasting.c | 335 ++++-
src/backend/commands/repack.c | 20 +-
src/backend/commands/tablecmds.c | 34 +
src/backend/replication/logical/decode.c | 7 +-
src/backend/replication/logical/proto.c | 2 +-
.../replication/logical/reorderbuffer.c | 210 ++-
src/backend/replication/pgoutput/pgoutput.c | 4 +-
src/backend/replication/pgrepack/pgrepack.c | 2 +-
src/backend/utils/adt/arrayfuncs.c | 6 +
src/backend/utils/fmgr/README | 4 +-
src/backend/utils/misc/guc_parameters.dat | 13 +
src/backend/utils/misc/guc_tables.c | 7 +
src/backend/utils/misc/postgresql.conf.sample | 2 +
src/include/access/detoast.h | 11 +
src/include/access/toast_internals.h | 74 ++
src/include/catalog/pg_proc.dat | 5 +
src/include/catalog/toasting.h | 1 +
src/include/utils/rel.h | 8 +
src/include/varatt.h | 69 +-
src/test/modules/injection_points/Makefile | 1 +
.../expected/repack_direct_toast.out | 276 ++++
src/test/modules/injection_points/meson.build | 1 +
.../specs/repack_direct_toast.spec | 225 ++++
src/test/regress/expected/direct_toast.out | 1140 +++++++++++++++++
src/test/regress/parallel_schedule | 2 +-
src/test/regress/sql/direct_toast.sql | 983 ++++++++++++++
40 files changed, 5680 insertions(+), 373 deletions(-)
create mode 100644 src/backend/access/common/README.toast
create mode 100644
src/test/modules/injection_points/expected/repack_direct_toast.out
create mode 100644
src/test/modules/injection_points/specs/repack_direct_toast.spec
create mode 100644 src/test/regress/expected/direct_toast.out
create mode 100644 src/test/regress/sql/direct_toast.sql
--
2.56.0.176.g3575e65682-goog
On Thu, Oct 8, 2026 at 10:23 PM Hannu Krosing wrote:
>
> Rebased as needed!
>
>
> On Mon, Oct 5, 2026 at 5:37 PM Hannu Krosing wrote:
> >
> > On Mon, Oct 5, 2026 at 3:18 PM Matthias van de Meent
> > wrote:
> > >
> > > On Wed, 30 Sept 2026 at 11:15, Hannu Krosing wrote:
> > > > On Tue, Sep 29, 2026 at 2:19 PM Matthias van de Meent
> > > > > wrote:
> > > > > I think it's feasible for btree to further optimize its storage format
> > > > > of toast -like fixed-size nonnull column definitions, allowing for
> > > > > more entries per page.
> > > >
> > > > This will still not address the need to do index cleanups when pruning
> > > > deleted toast, which avoiding the index entirely does.
> > >
> > > As I described in my other mail, it does not avoid index maintenance
> > > unless you avoid indexes on the toast table entirely, which this
> > > proposal doesn't.
> >
> > It does avoid index maintenance if you do not *use* any "plain" toast
> > If VACUUM only sees dead direct toast tuples it collects zero dead
> > tuple tids, and it does not run the index cleanup in case it has
> > collected no indead tuples.
> >
> > > > > > > > This is ensured by adding two new concepts to TOAST tables, even in
> > > > > > > > the existing TOAST 4-byte case: two new attributes and a partial
> > > > > > > > index. The existing attribute layer is moot when using one (4-byte
> > > > > > > > value) or the other (direct). This is a waste, and unlikely free.
> > > > > > > > The addition of a new partial index does not help much in that.
> > > > > > >
> > > > > > > It is not a *new* partial index, but the current PK is replaced with
> > > > > > > this. In case of online conversion, the current PK constraint is
> > > > > > > converted into this in-place.
> > > > > >
> > > > > > Don't you need a SHARE lock to build (replace) indexes?
> > > >
> > > > You need an exclusive lock for less than a millisecond to convert the
> > > > index in-place.
> > >
> > > Yes, but that still waits for other lockers to release, and newer
> > > lockers will conflict with this lock request and wait. A CREATE INDEX
> > > on a table will still cause writers to block when locking the table to
> > > add the new index definition.
> >
> > It does not do CREATE INDEX. It updates pg_index and pg_constraint dirtectly
> >
> > > > > > > Finally, and the biggest elephant in the room here by far.. VACUUM
> > > > > > > FULL, CLUSTER and REPACK *have* to be forbidden, because on rewrite
> > > > > > > each command rewrites the tids in the parent.
> > > > > >
> > > > > > They are only forbidden directly on the toast table, they work fine
> > > > > > when run on main table
> > > > >
> > > > > But the independent repack-ability of toast tables is a very valuable
> > > > > feature. Main tables have indexes that may be very expensive to
> > > > > rebuild. Yes, CONCURRENTLY could help, but it'll still take a
> > > > > possibly huge amount of resources, in time, CPU, memory, disk, IO.
> > > > > Repacking the toast table separately solves bloat issues in the toast
> > > > > table, and does not require the main table to be rebuilt, avoiding the
> > > > > related resource consumptions of index builds etc.
> > > >
> > > > Good Point. This is an issue when the main table which is much larger
> > > > and more expensive index-wise than toast and toast is already messed up
> > >
> > > It's more an issue when the main table's indexes are expensive to
> > > build. It doesn't really depend on the size of the main table data; a
> > > toast table+index is (with high certainty) always cheaper to rebuild
> > > on its own than a toast table+index with its main table and its
> > > indexes.
> >
> > But main table and Direct TOAST *without indexes* can be in many cases
> > cheaper to rebuild than toast table with indexes.
> >
> > > > (Though in this case I would expect the main problem to be the main
> > > > table, not toast)
> > >
> > > Why would it be? HOT updates on a table, with little data stored in
> > > the main table but a lot of columns pushed into TOAST (e.g. json(b)
> > > metadata fields) can definitely have a bloated TOAST table associated
> > > to a compact and well-organized main table.
> >
> > Sure. But I'd expect Direct TOAST to be able to avoid most of that
> > bloat via in-line pruning to UNUSED
> >
> > > > If toast is not messed up, in-line pruning should keep the TOAST table
> > > > growth in check.
> > >
> > > Fragmentation can be a problem in any table with row churn that
> > > doesn't reap the benefits of guaranteed HOT updates. I don't see how
> > > any new direct TOAST system completely avoids this.
> >
> > Nothing *completely* avoids this, at leas not with DBA doing some
> > amount of planning and tuning.
> >
> > > > > > and they also result in a clustered order
> > > > > > synchronized with main table, which is not the case when running on
> > > > > > toast table directly with the current design
> > > > >
> > > > > Yes, repacking the toast table won't reorder the toast table to heap
> > > > > order, but in my humble opinion that's OK; just de-bloating the toast
> > > > > table and index is enough for some workloads.
> > > >
> > > > It is for some.
> > > >
> > > > And for even more workloads you do not need de-bloating at all, even
> > > > with current design.
> > > >
> > > > Direct Toast allows you to not get bloated in the first place because
> > > > of inline pruning and really cheap vacuum which needs to jsut look at
> > > > dirty pages and fully skip the index cleanup.
> > >
> > > Why would vacuum only need to look at dirty pages? Visibility
> > > (cleanup) horizons frequently outlast the current checkpoint, and can
> > > outlast even the buffer pool if/when replication is enabled, so only
> > > looking at dirtied pages is a very short-sighted method of cleanup.
> >
> > Again, it's not absolute solution. I can always costruct a use case
> > where the most sensible solution is to shut down your business for a
> > few hours and run VACUUM FULL or CLUSTER
> >
> > > And I don't see why skipping index cleanup would be allowable in any world.
> >
> > We do skip index cleanup when we prune other HEAP_ONLY_TUPLES.
> >
> > It is allowable exactly because there are no index pointers to them.
> >
> > Same for Direct TOAST tuples
> >
> > > > > > > That's a legal
> > > > > > > defensive set of commands because it is possible to reclaim bloat from
> > > > > > > TOAST relations directly, and I doubt that we'd *ever* want to drop
> > > > > > > this property, especially based on the benchmark claim of upthread.
> > > > > >
> > > > > > If you have a workload that updates toasted columns this results in
> > > > > > these being sprinkled all over the toast table, with random oids, so
> > > > > > even CLUSTER will not put them in the same order as main table.
> > > > >
> > > > > What do you mean by sprinkled all over and random OIDs?
> > > > > Toast IDs that are generated at about the same time will generally be
> > > > > closely related, and after CLUSTER these will be close together in the
> > > > > toast table, for both OID (very likely) and OID8 (practically
> > > > > guaranteed).
> > > > >
> > > > > They will definitely be in OID order, so what is the
> > > > > sprinkling randomness about?
> > > >
> > > > UPDATE will generate a new toasted value with newly allocated oid. If
> > > > some fields are updated late then they will not be close.
> > >
> > > What do you mean by late update?
> >
> > When say you have multiple toasted values and you initially only
> > insert one and other coime later, or when there are workflows that
> > keep updating some of the toasted columns.
> >
> > > The SQL script you included didn't
> > > really show much other than that TOASTing values close in time
> > > produces close-in-value toast IDs, which is expected. And those
> > > close-in-value IDs are likely placed near eachother (and definitely
> > > placed near eachother after a CLUSTER of the toast table)
> >
> > I can send you another script which you can then run for ~10 days (I
> > did) to verify that thins DO get messed up
> >
> > > > > > > This is why you want to run REPACK on the main table if you need to
> > > > > > > recover space AND also care about performance.
> > > > > > > In my tests autovacuum kept the direct toast table in shape more
> > > > > > > efficiently, most likely because it could skip the expensive index
> > > > > > > cleanup phase, so there was less bloat accumulating.
> > > > > >
> > > > > > How do you fit these claims together?
> > > > > >
> > > > > > 1. "zero-downtime / zero-migration switch to direct toast (and back)"
> > > > > > (from the start of the thread);
> > > > > > 2. No index cleanup phase
> > > > > >
> > > > > > If you can do a zero-migration change, old data will still have old
> > > > > > pointers, and those must be looked up through the index.
> > > > > > Once a table has an index, its vacuum MUST apply an index cleanup
> > > > > > phase, lest it contain any references to LP_DEAD line pointers still
> > > > > > present in the table. Note that LP_DEAD entries don't carry
> > > > > > information about which index(es) do or don't contain references to
> > > > > > that item, so you can't distinguish between included in and excluded
> > > > > > from the index -- all dead items must be processed.
> > > >
> > > > Latest few patch sets have includes a change to pruning which prunes
> > > > deleted direct toast chunks to LP_UNUSED directly
> > > >
> > > > So if you have been updating only direct toast pointers there will be
> > > > no dead tids collected.
> > >
> > > I categorically disagree with such a change. Index cleanup _must_
> > > happen for non-HOT tuples when the table contains at least one
> > > non-summarizing index.
> >
> > Can you elaborate, whay do you think you need to perform index cleanup
> > when the firs pass deleted no rows that had indexes pointing to them ?
> >
> > > > > > > > A
> > > > > > > > worst thing to me is that this seems to entirely disable their use due
> > > > > > > > to this in v2-0004, cluster_rel() or cluster.c:
> > > > > > > > + if (OldHeap->rd_rel->relkind == RELKIND_TOASTVALUE)
> > > > > > > > [..,]
> > > > > > > > + if (OldHeap->rd_att->natts >= 4 &&
> > > > > > > >
> > > > > > > > The two new attributes are added *unconditionally*.
> > > > > > >
> > > > > > > Yes, but they are not used if you keep using only 4-byte OIDs. In that
> > > > > > > case they only appear in the catalog tables.
> > > > > >
> > > > > > That's not accurate; these columns will hold NULL values, which means
> > > > > > they'll bloat OID-toast tuples with a NULL bitmap, which will be one
> > > > > > MAXALIGN quantum in size in this table definition.
> > > >
> > > > There is always space for one byte of null bitmap after the 23-byte
> > > > tuple headers, so up to 8 attributes can have their null bitmap for
> > > > free.
> > > >
> > > > AND even now the three user attributes are not declared NOT NULL
> > >
> > > Correct, but this new scheme would change these into nullable
> > > attributes, requiring much more effort from every system to make sure
> > > they're accessing the right tuple data.
> >
> > Again, they ALREADY are nullable,
> >
> > "> > AND even now the three user attributes are NOT declared NOT NULL"
> >
> > Can you elaborate on "requiring much more effort from every system" -
> > which systems do you have in mind ?
> >
> > > > > > No, we don't recheck the valueid in the heaptuple. However, we do
> > > > > > check that the chunk counter matches the expected values, and that's
> > > > > > something that won't be possible in the direct toast design -- there
> > > > > > is nothing in the toast pointer nor the toast tuple that links it to
> > > > > > its own identity, especially not outside the scope of MVCC snapshots.
> > > >
> > > > Do you think it os a valuable property to have ?
> > >
> > > Yes. We have an active problem with SnapshotAny-scans in DDL that
> > > detoast recently-dead tuples' removed TOAST pointers, and the checks
> > > that we do have in place actively protect against real corruptions.
> > > It's bad we're hitting ERROR paths here, but it's much better than the
> > > alternative.
> >
> > Can you point me to the places where this is done ?
> >
> > > > > > > > give the option for new tables to choose this method
> > > > > > > > (for the reasons listed in the last two paragraphs, I guess no anyway,
> > > > > > > > but that's what I would recommend if following up).
> > > > > > >
> > > > > > > The main reason you may want to REPACK *only* the toast table is that
> > > > > > > it currently behaves badly, partly because of expensive toast index
> > > > > > > cleanups.
> > > > > > >
> > > > > > > If you want performance back, you want to REPACK the main table, which
> > > > > > > fixes the random placement of toasted field problem.
> > > > > >
> > > > > > It is very feasible for the main table to be packed normally, whilst
> > > > > > the toast table becomes very bloated; this happens frequently when
> > > > > > large toasted columns get updated every once in a while with vacuum
> > > > > > and/or page pruning running just frequently enough to allow the main
> > > > > > table's tuple to fit back on the same page. REPACKing the main table
> > > > > > requires more locks and possibly much more time than just repacking
> > > > > > the toast table (one btree index rebuild vs numerous arbitrarily
> > > > > > defined index rebuilds). I don't think trading the independent
> > > > > > repack-ability of a toast table for a bit of performance with small
> > > > > > toasted values is a reasonable tradeoff for every user.
> > > >
> > > > Not just small toast values, large ones can also be made faster as a follow-up.
> > > >
> > > > Once you have a chunk offset array, you can start putting one large
> > > > chunk per page instead of four small ones.
> > > >
> > > > And I am not claiming it is best for all corner cases, likke already
> > > > having an old bloated toast table wgich needs repacking. That one
> > > > should be repacked before enabling direct toast. Once Direct TOAST is
> > > > enabled you can keep the bloat down.
> > >
> > > How do you do that? Direct toast pins the location of a toasted value
> > > into a specific physical page, you can't move it. If there's a churn
> > > in toasted values that temporarily can't be removed, and the newest
> > > (and surviving) value is located on the final page of the toast
> > > relation, how would you de-bloat that toast table?
> >
> > Basically the same way I have been doing on-line de-bloating since 2006 :)
> >
> > Find the main row pointing to that toasted value, then update the
> > toasted value until it does not fit on that page and then it moves to
> > a lower one.
> >
> > See the attachce python script for doing this on normal table, this
> > can be easily adapted to Direct TOAST, especially if we start adding
> > back-pinters to toast chunks
> >
> > I know that the orthodox PostgreSQL de-bloating in this case either
> > lcoking everything and running VACUUM FULL or REPACK
> >
> > > > > > > ## In conclusion:
> > > > > > >
> > > > > > > I still think that these three goals
> > > > > > > - zero-downtime upgrade
> > > > > > > - less space used
> > > > > > > - faster performance
> > > > > > > are equally important and should be tackled together.
> > > > > > >
> > > > > > > As for your performance concerns, can you point me to use cases where
> > > > > > > you think the current oid4 can be faster?
> > > > > > > It does not have to be very detailed, just a general workload description helps.
> > > > > >
> > > > > > I'd consider huge toasted values as a case where index lookups can be
> > > > > > faster, because it automatically gains the benefits of performance
> > > > > > improvements in the index lookup path. The Direct Toast path needs to
> > > > > > manually build this feature.
> > > >
> > > > Very performant is still slower than not doing it at all.
> > >
> > > True. But in this case we do need (a way to handle large
> > > column values). And given the page size limit, we'll have to cut up
> > > large values one way or another. And given that cutting up values,
> > > we'll probably want to avoid fragmenting the table.
> >
> > We can come back to this discussion once these benefits of performance
> > improvements in the index lookup path materialize.
> >
> > > > Currently DToast is roughly the same speed for huge toast values when
> > > > indexes are in memory, because the data page fetches dominate
> > > > It is significantly faster for cold caches.
> > > >
> > > > But Direct TOAST structure allows it to be made even faster by adding
> > > > fored readahead and making use of direct io parallelism
> > >
> > > Which part of indexing won't allow that same optimization to be
> > > applied? Direct toast seems to be not dissimilar from a specialized
> > > inlined index; and these should allow similar features to be applied.
> > > The time spent optimizing the toast system for its own bespoke
> > > solution might better be spent on making the index path work better
> > > for TOAST.
> >
> > You can't really avoid accessing the index for index lookup paths,
> > which by default involve fetching, pinning and locking the index
> > pages. You can not make that faster than not doing any of that.
> >
> > The Indexed toast is currently a few tens of percent slower even if
> > everything is in shared buffers.
> >
> >
> > > > > > And please test the performance difference between repacking a bloated
> > > > > > toast table vs repacking its main table with expensive-to-build
> > > > > > indexes (e.g. several gin on jsonb, pg_trgm with large text, HNSW,
> > > > > > etc.). I think the cost of fixing bloat in the toast table will be
> > > > > > much lower than repacking the main table+indexes with it.
> > > >
> > > > I would rather make avoiding the need to repack a priority :)
> > > >
> > > > There will always be ways to mess up your database.
> > >
> > > Yes, but I'd like to avoid raising the minimum cost of cleaning up
> > > messes that have already been made. I believe there is no reason
> > > that's good enough to require a strong coupling between toast and main
> > > table repacking.
> >
> > There are a few proposals pfor bringing back the overflow pages from
> > the 1976 Ingres design. That would really make the coupling tight.
> >
> > > You may be able to get around this coupling by storing the TID + a
> > > "generation" ID, where repacking the toast table causes new generation
> > > IDs to be produced, and old generations are looked up in an index by
> > > [generation id, old head TID -> head TID], or even rewriting the
> > > chunks into the index as [generation_id, old TID, chunk_id -> chunk
> > > tid].
> > > You'd keep most of the performance of direct toast in the common case
> > > (values created after table created & after last repack) without
> > > throwing out independent repackability.
> >
> > I have been working on a separate proposal doing something similar for
> > GENERATED ALWAYS AS *ROW* IDENTITY which mostly uses TID expanded to
> > 64 bits as ROW id and only puts the "row id" into a partial index if
> > the row has to move off the original page and hot chains stop working
> > for lookup :)
> >
> > This is closely related to my work on enabling REPLICA IDENTITY ROWID,
> > which uses tid as identity.
> >
> > > Note that TOAST tables can be the largest part of a table's total
> > > storage cost, or secondary only after the main table's indexes.
> > > Rebuilding it independently is exceedingly likely to be worth the
> > > effort, vs not cleaning up.
> >
> > Yes, I have seen real cases of running out of toast oids wheremore
> > than 8TB of a total 9TB table was toast+toast index.
> >
> > In my extreme test running 10 days of massive updates on small toasted
> > columns the Toast INDEX became the largest part of storage cost in
> > case of indexed toast.
> >
> > Direct TOAST did not bloat the main TOAST table much, and of course it
> > did not have the toast index at all.
> >
> > > > But this makes me realise that I should only add the Direct TOAST
> > > > columns (and thus disable direct repack) if the corresponding table
> > > > option toast_flavour=direct is set so people who want to retain this
> > > > option can do so.
> > >
> > > Except that you can't disable the direct toast -enabled "never repack
> > > again" poison once it's there, and I think that that is not an
> > > acceptable tradeoff.
> >
> > You can still repack, just you have to do it together with main table.
> >
> > > > That said, do you have any specific concerns about having partial
> > > > indexes in catalogs?
> > >
> > > They require relatively complicated allocations and handling in
> > > critical paths, so I like to avoid them whenever I can. We can make
> > > it work, for sure, but I'm not sure it's worth it for toast;
> > > especially given that expressions aren't exactly cheap to store in
> > > memory.
> >
> > Using from low-level system functions is allowed to just not care.
> >
> > And user query already do the right thing anyway, because the always
> > *do* base their actions on what is in system tables.
> >
> > > FYI, there is an ongoing thread over at [0] discussing partial indexes
> > > in catalogs for other purposes.
> >
> > Thank, will definitely rtake a look.
> >
> >
> > > Kind regards,
> > >
> > > Matthias van de Meent
> > > Databricks (https://www.databricks.com)
> > >
> > > [0] https://www.postgresql.org/message-id/179089136170.117434.3768797469846977966%40gmail.com