Re: Fix race in background worker termination for database

From: Michael Paquier <michael(at)paquier(dot)xyz>
To: Chao Li <li(dot)evan(dot)chao(at)gmail(dot)com>
Cc: "Aya Iwata (Fujitsu)" <iwata(dot)aya(at)fujitsu(dot)com>, PostgreSQL-development <pgsql-hackers(at)lists(dot)postgresql(dot)org>, Michael Paquier <michael(dot)paquier(at)gmail(dot)com>
Subject: Re: Fix race in background worker termination for database
Date: 2026-07-29 04:54:34
Message-ID: ammHitR7j0DqEhAH@paquier.xyz
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Sat, Jul 25, 2026 at 10:29:18AM +0800, Chao Li wrote:
> Okay, I was being overly cautious.

So, I have looked at that, and after more testing the problem cannot
really happen manually with worker_spi. Gathering the facts:
1) We know that we need an interruptible worker needs to be killed
between the BackendPidGetProc() and the moment we read databaseId, so
as its proc slot is killed.
2) We know is that the bgworkers use their own free list for proc
slots.
3) We hold BackgroundWorkerLock in exclusive mode when doing a
database or tablespace DDL to scan for interruptible workers to
signal.

Parallel workers spawned and dynamic workers need to go through the
registration path, where a BackgroundWorkerLock is required, so we
cannot do proc slot manipulations for these while attempting a
TerminateBackgroundWorkersForDatabase() for the bgworker free list.

Saying that, as far as I can see, there is one subtle case where a
proc slot could be reused in this window: a postmaster does not use
BackgroundWorkerLock when restarting a worker that's been statically
started. So if a static worker stops, and is then restarted according
to its bgw_restart_time, then it could reuse the pgproc slot of the
interruptible worker. While very unlikely, the problem could in
theory happen (in practice, not really). I don't see a reason to not
acquire a pgproc as proposed, so I'll go fix the issue and adjust the
locking.
--
Michael

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message vignesh C 2026-07-29 04:57:04 Re: Race between pg_dump and ALTER SEQUENCE can cause read failure
Previous Message Corey Huinker 2026-07-29 04:37:38 Re: More jsonpath methods: translate, split, join