Avoid calling SetMatViewPopulatedState if possible

Started by cca55078 months ago11 messageshackers
Jump to latest
#1cca5507
cca5507@qq.com

Hi,

During refresh matview, we call SetMatViewPopulatedState unconditionally even
if the value doesn't change. Attach a small patch to optimize it.

--
Regards,
ChangAo Chen

Attachments:

v1-0001-Avoid-calling-SetMatViewPopulatedState-if-possibl.patchapplication/octet-stream; charset=utf-8; name=v1-0001-Avoid-calling-SetMatViewPopulatedState-if-possibl.patchDownload+2-2
#2David Geier
geidav.pg@gmail.com
In reply to: cca5507 (#1)
Re: Avoid calling SetMatViewPopulatedState if possible

Hi,

On 10.04.2026 05:36, cca5507 wrote:

During refresh matview, we call SetMatViewPopulatedState unconditionally even
if the value doesn't change. Attach a small patch to optimize it.

Thanks for sharing this patch.

While being a simple patch, it would be good to know what actual use
cases this change improves on and by how much. Can you share a test case
and/or performance data?

--
David Geier

#3cca5507
cca5507@qq.com
In reply to: David Geier (#2)
Re: Avoid calling SetMatViewPopulatedState if possible

Hi,

Thanks for your reply!

While being a simple patch, it would be good to know what actual use
cases this change improves on and by how much. Can you share a test case
and/or performance data?

The improvement of performance is small, so it's hard to observe it. But I think
the patch is still useful because we can avoid generating dead pg_class tuple:

create table t(a int);
create materialized view m as select a from t;
create unique index on m(a);
select ctid from pg_class where relname = 'm';
refresh materialized view concurrently m;
select ctid from pg_class where relname = 'm';

Before the patch, the ctid will change every time we refresh the matview.

--
Regards,
ChangAo Chen

#4David Geier
geidav.pg@gmail.com
In reply to: cca5507 (#3)
Re: Avoid calling SetMatViewPopulatedState if possible

On 05.05.2026 13:58, cca5507 wrote:

While being a simple patch, it would be good to know what actual use
cases this change improves on and by how much. Can you share a test case
and/or performance data?

The improvement of performance is small, so it's hard to observe it. But I think
the patch is still useful because we can avoid generating dead pg_class tuple:

create table t(a int);
create materialized view m as select a from t;
create unique index on m(a);
select ctid from pg_class where relname = 'm';
refresh materialized view concurrently m;
select ctid from pg_class where relname = 'm';

Before the patch, the ctid will change every time we refresh the matview.

Yeah, that's kind of what I had in mind as I wasn't expecting the
performance to matter much here. Avoiding the bloat seems generally
reasonable.

But refreshing a materialized view doesn't only change relispopulated
but also columns like relfilenode, relpages, relhasindex, etc. Doesn't
changing these columns during REFRESH MATERIALIZED VIEW make your
optimization applicable in a lot less cases?

I'm actually wondering why it works at all, even in the example you
gave. Because I thought that even when nothing has changed the pg_class
row is updated for more columns than just relispopulated.

--
David Geier

#5cca5507
cca5507@qq.com
In reply to: David Geier (#4)
Re: Avoid calling SetMatViewPopulatedState if possible

But refreshing a materialized view doesn't only change relispopulated
but also columns like relfilenode, relpages, relhasindex, etc. Doesn't
changing these columns during REFRESH MATERIALIZED VIEW make your
optimization applicable in a lot less cases?

I don't think so. If we can skip SetMatViewPopulatedState(), we avoid generating
a dead pg_class tuple in all cases.

I'm actually wondering why it works at all, even in the example you
gave. Because I thought that even when nothing has changed the pg_class
row is updated for more columns than just relispopulated.

"refresh materialized view concurrently" is done by doing DELETE + INSERT
to the matview directly, so only relispopulated will change before the patch.
After the patch, the pg_class row don't change anymore.

--
Regards,
ChangAo Chen

#6ZizhuanLiu X-MAN
44973863@qq.com
In reply to: cca5507 (#5)
Re: Avoid calling SetMatViewPopulatedState if possible

HI, ChangAo Chen, David Geier , hackers 

>> But refreshing a materialized view doesn't only change relispopulated
>> but also columns like relfilenode, relpages, relhasindex, etc. Doesn't
>> changing these columns during REFRESH MATERIALIZED VIEW make your
>> optimization applicable in a lot less cases 
>
>I don't think so. If we can skip SetMatViewPopulatedState(), we avoid generating
>a dead pg_class tuple in all cases.
>
>> I'm actually wondering why it works at all, even in the example you
>> gave. Because I thought that even when nothing has changed the pg_class
>> row is updated for more columns than just relispopulated.
>
>"refresh materialized view concurrently" is done by doing DELETE + INSERT
>to the matview directly, so only relispopulated will change before the patch.
>After the patch, the pg_class row don't change anymore.

1.Regarding pg_class.relispopulated
This column was introduced in PostgreSQL 9.3 specifically for materialized views. 
Conceptually, the state of "IsScannable" is equivalent to and fully dependent on relispopulated.
This flag(relispopulated) is also used across multiple features, including COPY/pg_repack/pg_dump.
For the definitions of the populated and scannable states of materialized views, please refer to the official documentation:
    https://www.postgresql.org/docs/devel/sql-creatematerializedview.html
    https://www.postgresql.org/docs/devel/sql-refreshmaterializedview.html

2.Current status
As ChangAo Chen mentioned and verified via tests, and based on my own research and testing,
I agree with this conclusion:
    If pg_class.relispopulated does not actually change, there is *no need* to invoke SetMatViewPopulatedState().
Skipping this call will also avoid executing the subsequent call chain:
    CatalogTupleUpdate() -> simple_heap_update() -> heap_update().
    This helps prevent dead tuples from being generated, and also reduces overhead on underlying mechanisms
    including locks, transactions, WAL (xlog), as well as IPC contention and synchronization. 

3.Regarding updates to attributes in pg_class
> But refreshing a materialized view doesn't only change relispopulated
> but also columns like relfilenode, relpages, relhasindex, etc. Doesn't
> changing these columns during REFRESH MATERIALIZED VIEW make your
> optimization applicable in a lot less cases?
To clarify: SetMatViewPopulatedState() is dedicated solely to modifying relispopulated. 
Columns such as relfilenode, relpages and relhasindex are updated by other separate routines.

4. About SetMatViewPopulatedState() and its caller
There are two possible ways to implement this optimization:
    --The first approach is to refactor SetMatViewPopulatedState() to handle the check internally:
         If ((Form_pg_class) GETSTRUCT(tuple))->relispopulated != newstate, then perform the actual update; otherwise, do nothing.
    --The second approach is to perform the check inside the caller RefreshMatViewByOid(), as implemented in ChangAo Chen’s patch.
        I also noticed that intorel_startup() in createas.c follows the same design pattern — letting the caller handle the check before invoking the callee. 

5. A small suggestion
After further consideration, I suggest using the condition:
    if (RelationIsPopulated(matviewRel) != !skipData)
This is much more readable and intuitive compared to the original:
    if (RelationIsPopulated(matviewRel) == skipData)
Especially when paired with the original call:
    SetMatViewPopulatedState(matviewRel, !skipData);

Additionally, avoiding unnecessary updates and thus preventing dead tuples is especially valuable in BI/OLAP environments that use many materialized views and refresh them frequently (daily or hourly).

6. About Testing
--The new patch passes all PostgreSQL regression tests:
  xman@xman_lzz:~/patch_1/build/testrun/regress/regress$ grep -n matview regression.out
128:# parallel group (20 tests):  init_privs drop_operator security_label password lock object_address tablesample collate groupingsets replica_identity spgist gin matview identity gist generated_stored rowsecurity brin join_hash privileges
137:ok 126       + matview                                 47396 ms
xman@xman_lzz:~/patch_1/build/testrun/regress/regress$

--I have also checked the output files and expected files for the materialized view regression tests, and they are identical:
  xman@xman_lzz:~$ ls -l /home/xman/patch_1/postgres/src/test/regress/expected/matview.out
-rw-rw-r-- 1 xman xman 24946 May 25 22:29 /home/xman/patch_1/postgres/src/test/regress/expected/matview.out
xman@xman_lzz:~$ ls -l /home/xman/patch_1/build/testrun/regress/regress/results/matview.out
-rw-rw-r-- 1 xman xman 24946 May 27 23:05 /home/xman/patch_1/build/testrun/regress/regress/results/matview.out
xman@xman_lzz:~$ diff /home/xman/patch_1/postgres/src/test/regress/expected/matview.out /home/xman/patch_1/build/testrun/regress/regress/results/matview.out
xman@xman_lzz:~$ echo $?
0
xman@xman_lzz:~$ 

The above is what I have found so far. Please feel free to correct me if I have any misunderstandings.
Thanks,
--
Zizhuan Liu (X-MAN) 
44973863@QQ.COM

Attachments:

t139276_6
v2-0001-Avoid-calling-SetMatViewPopulatedState-if-possibl.patchapplication/octet-stream; charset=utf-8; name=v2-0001-Avoid-calling-SetMatViewPopulatedState-if-possibl.patchDownload+2-2
#7cca5507
cca5507@qq.com
In reply to: ZizhuanLiu X-MAN (#6)
Re: Avoid calling SetMatViewPopulatedState if possible

Hi Zizhuan,

Thanks for your careful review!

5. A small suggestion
After further consideration, I suggest using the condition:
    if (RelationIsPopulated(matviewRel) != !skipData)
This is much more readable and intuitive compared to the original:
    if (RelationIsPopulated(matviewRel) == skipData)
Especially when paired with the original call:
    SetMatViewPopulatedState(matviewRel, !skipData);

Both are ok for me.

--
Regards,
ChangAo Chen

#8Fujii Masao
masao.fujii@gmail.com
In reply to: cca5507 (#7)
Re: Avoid calling SetMatViewPopulatedState if possible

On Thu, Jun 18, 2026 at 6:28 PM cca5507 <cca5507@qq.com> wrote:

5. A small suggestion
After further consideration, I suggest using the condition:
if (RelationIsPopulated(matviewRel) != !skipData)
This is much more readable and intuitive compared to the original:
if (RelationIsPopulated(matviewRel) == skipData)
Especially when paired with the original call:
SetMatViewPopulatedState(matviewRel, !skipData);

Both are ok for me.

Thanks for the patch! I went with the following form:

if (RelationIsPopulated(matviewRel) != !skipData)
SetMatViewPopulatedState(matviewRel, !skipData);

Attached is an updated patch. I also adjusted the nearby comment and
expanded the commit message to explain the unnecessary pg_class update
and resulting dead tuple generation.

Barring any objections, I'm thinking to commit this.

Regards,

--
Fujii Masao

Attachments:

t139276_8
v3-0001-Avoid-unnecessary-matview-populated-state-updates.patchapplication/octet-stream; name=v3-0001-Avoid-unnecessary-matview-populated-state-updates.patchDownload+4-4
#9cca5507
cca5507@qq.com
In reply to: Fujii Masao (#8)
Re: Avoid calling SetMatViewPopulatedState if possible

Attached is an updated patch. I also adjusted the nearby comment and
expanded the commit message to explain the unnecessary pg_class update
and resulting dead tuple generation.

Thanks for the v3 patch, LGTM!

--
Regards,
ChangAo Chen

#10Adam Brusselback
adambrusselback@gmail.com
In reply to: cca5507 (#9)
Re: Avoid calling SetMatViewPopulatedState if possible

Hi,

Attached is an updated patch. I also adjusted the nearby comment and
expanded the commit message to explain the unnecessary pg_class update
and resulting dead tuple generation.

+1 on the change. I have the same thing in the REFRESH ... WHERE patch
[1]: /messages/by-id/CAMjNa7eFzTQ5=oZMQiB2bMkez5KP4A77JC7SRjeVEkOrh7cUHw@mail.gmail.com

One thing worth adding to the justification: the dead tuple isn't the
only cost. The CatalogTupleUpdate() also sends an SI message, so every
call invalidates the relcache entry for the MV in every backend,
including the caller's own, and that discards cached plans referencing
it. On an MV that gets refreshed often and is already populated, the
repeated invalidation costs more than the dead tuple does.

A partial refresh hits this on every call, which is how I ran into it.
That patch caches the prepared refresh plans per MV to get the per-call
cost down, and until I added the check the invalidation was marking them
invalid on every refresh, so the cache wasn't buying anything.

I had put the check inside SetMatViewPopulatedState() rather than at the
call site, but there's no functional difference between the two. Both
call sites are covered either way, so that's just a style preference on
my part. I'll rebase onto whatever form goes in.

Thanks,
Adam

[1]: /messages/by-id/CAMjNa7eFzTQ5=oZMQiB2bMkez5KP4A77JC7SRjeVEkOrh7cUHw@mail.gmail.com
/messages/by-id/CAMjNa7eFzTQ5=oZMQiB2bMkez5KP4A77JC7SRjeVEkOrh7cUHw@mail.gmail.com

#11Fujii Masao
masao.fujii@gmail.com
In reply to: Adam Brusselback (#10)
Re: Avoid calling SetMatViewPopulatedState if possible

On Tue, Aug 11, 2026 at 3:29 AM Adam Brusselback
<adambrusselback@gmail.com> wrote:

+1 on the change. I have the same thing in the REFRESH ... WHERE patch
[1], so I'd like to see it go in on its own.

One thing worth adding to the justification: the dead tuple isn't the
only cost. The CatalogTupleUpdate() also sends an SI message, so every
call invalidates the relcache entry for the MV in every backend,
including the caller's own, and that discards cached plans referencing
it. On an MV that gets refreshed often and is already populated, the
repeated invalidation costs more than the dead tuple does.

Thanks for the review and for sharing your analysis! I've pushed the patch.

Regards,

--
Fujii Masao