Properly detoast data in brin_form_tuple
authorTomas Vondra <tomas.vondra@postgresql.org>
Fri, 6 Nov 2020 23:41:52 +0000 (00:41 +0100)
committerTomas Vondra <tomas.vondra@postgresql.org>
Fri, 6 Nov 2020 23:41:52 +0000 (00:41 +0100)
commitd2d3a4bd33d2c0b1ffb1a4f6db6b866619134a4b
tree09f0223e24597da3ba5cbb587fe5157cdfdf97e1
parent43c2e97ed45d665b1a8ef0fa3d20e7c5492f5f2b
Properly detoast data in brin_form_tuple

brin_form_tuple failed to consider the values may be toasted, inserting
the toast pointer into the index. This may easily result in index
corruption, as the toast data may be deleted and cleaned up by vacuum.
The cleanup however does not care about indexes, leaving invalid toast
pointers behind, which triggers errors like this:

  ERROR:  missing chunk number 0 for toast value 16433 in pg_toast_16426

A less severe consequence are inconsistent failures due to the index row
being too large, depending on whether brin_form_tuple operated on plain
or toasted version of the row. For example

    CREATE TABLE t (val TEXT);
    INSERT INTO t VALUES ('... long value ...')
    CREATE INDEX idx ON t USING brin (val);

would likely succeed, as the row would likely include toast pointer.
Switching the order of INSERT and CREATE INDEX would likely fail:

    ERROR:  index row size 8712 exceeds maximum 8152 for index "idx"

because this happens before the row values are toasted.

The bug exists since PostgreSQL 9.5 where BRIN indexes were introduced.
So backpatch all the way back.

Author: Tomas Vondra
Reviewed-by: Alvaro Herrera
Backpatch-through: 9.5
Discussion: http://postgr.es/m/20201001184133.oq5uq75sb45pu3aw@development
Discussion: http://postgr.es/m/20201104010544.zexj52mlldagzowv%40development
src/backend/access/brin/brin_tuple.c
src/test/regress/expected/brin.out
src/test/regress/sql/brin.sql