Re: Fix relation statistics around transactional TRUNCATE

From: Sami Imseih <samimseih(dot)pg(at)gmail(dot)com>
To: Bertrand Drouvot <bertranddrouvot(dot)pg(at)gmail(dot)com>
Cc: pgsql-hackers(at)lists(dot)postgresql(dot)org, David Rowley <dgrowleyml(at)gmail(dot)com>, Alvaro Herrera <alvherre(at)kurilemu(dot)de>, Michael Paquier <michael(at)paquier(dot)xyz>
Subject: Re: Fix relation statistics around transactional TRUNCATE
Date: 2026-12-02 00:16:09
Message-ID: CAN12+Y+QHR1SUEYbDdxghQzMgw5cZiRD=P28vEv56QUP5D7b4Q@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

While working with Claude today to find more issues in [1], I found another
issue related to this class of truncate problems, which is not addressed
in the attached patchset.

```
postgres=# CREATE TABLE tt(a int);
INSERT INTO tt SELECT generate_series(1, 5);
SELECT pg_stat_force_next_flush();
SELECT 1; -- next statement, so the forced flush has happened
CREATE TABLE
INSERT 0 5
pg_stat_force_next_flush
--------------------------

(1 row)

?column?
----------
1
(1 row)

postgres=# CREATE PROCEDURE tt_probe() LANGUAGE plpgsql AS $$
BEGIN
TRUNCATE tt;
COMMIT;
INSERT INTO tt VALUES (1);
END $$;
CALL tt_probe();
SELECT pg_stat_force_next_flush();
SELECT 1;

SELECT n_live_tup, n_dead_tup FROM pg_stat_user_tables WHERE relname = 'tt';
CREATE PROCEDURE
CALL
pg_stat_force_next_flush
--------------------------

(1 row)

?column?
----------
1
(1 row)

n_live_tup | n_dead_tup
------------+------------
6 | 0
(1 row)
```

n_live_tup should be 1 here, since the TRUNCATE inside the procedure
committed.

The cause seems to be AtEOXact_PgStat_Relations() overwriting
tab.truncdropped at commit. The TRUNCATE's commit sets it on the
table's pending entry, but the INSERT commits in its own transaction
before that entry is flushed, and its commit sets it back to false.
So the flush never resets n_live_tup, and the 5 rows from before the
TRUNCATE remain. pgstat_twophase_postcommit() has the same assignment.
Both are due to d42358efb16, which goes back to 9.5, so this is an ancient case.

I do not have a patch for it yet.

[1] https://www.postgresql.org/message-id/avwEcRxMmL7o/hfm%40bdtpg

--
Sami Imseih
Amazon Web Services (AWS)

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Michael Paquier 2026-12-02 00:28:43 Re: pgstat: Flush some statistics within running transactions, take 2
Previous Message Ajin Cherian 2026-12-02 00:13:41 Re: [PATCH] Preserve replication origin OIDs in pg_upgrade