Re: Fix race in background worker termination for database

From: Chao Li <li(dot)evan(dot)chao(at)gmail(dot)com>
To: Michael Paquier <michael(at)paquier(dot)xyz>
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-25 02:29:18
Message-ID: AAEF1B3D-47D5-4F70-9070-CFC3DBBB6A42@gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

> On Jul 25, 2026, at 07:10, Michael Paquier <michael(at)paquier(dot)xyz> wrote:
>
> On Fri, Jul 24, 2026 at 01:32:05PM +0000, Aya Iwata (Fujitsu) wrote:
>> I'm not sure how long the PGPROC might be reused or modified after it is
>> retrieved, but it's true that the scenario you're describing could occur
>> depending on the timing.
>>
>> I think this fix looks good. I would appreciate hearing what the other members think.
>
> Hmm. The case of an interruptible bgworker terminating itself between
> the moment BackendPidGetProc() is called and the moment we read the
> databaseId, meaning that the PGPROC entry gets cleaned with the same
> proc entry being reused afterwards? Say (not tested myself, just
> hand-waving for now):
> - Call BackendPidGetProc()
> - Hold a breakpoint with the proc pointer to enlarge the window.
> - Manipulate the PGPROC slots and change a databaseId.
> - Terminate incorrect database.
>
> That would warrant a WithLock() call with a procarray lock held until
> we check the contents of the procarray entry.

Thanks for confirming.

> Keeping the DEBUG2
> inside or outside the LWLock does not matter much, that's a LWLock we
> talk about, not a spinlock.
> --
> Michael

Okay, I was being overly cautious.

PFA v2:

* Moved elog() into the lock section and removed the now-unneeded local variable “terminate".
* Incorporated Haibo’s suggestion to copy slot->pid before acquiring the lock.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/

Attachment Content-Type Size
v2-0001-Protect-PGPROC-lookup-when-terminating-background.patch application/octet-stream 2.0 KB

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Michael Paquier 2026-07-25 03:54:03 Re: NULL pointer dereference in syslogger with load_libraries() and -DEXEC_BACKEND at startup
Previous Message Fujii Masao 2026-07-25 01:36:14 Re: Fix publisher-side sequence permission reporting