Re: Improve LWLock tranche name visibility across backends

Sami Imseih <samimseih@gmail.com>

From: Sami Imseih <samimseih@gmail.com>
To: Nathan Bossart <nathandbossart@gmail.com>
Cc: Rahila Syed <rahilasyed90@gmail.com>, Bertrand Drouvot <bertranddrouvot.pg@gmail.com>, Tom Lane <tgl@sss.pgh.pa.us>, Andres Freund <andres@anarazel.de>, pgsql-hackers <pgsql-hackers@postgresql.org>
Date: 2025-09-04T17:30:27Z
Lists: pgsql-hackers
> I'm having some regrets about the changes to RequestNamedLWLockTranche().
> Specifically, when it is first called, it immediately allocates an array
> big enough to hold 256 requests (~17 KB), whereas it used to only allocate
> space for 16 requests (~1 KB) and resize as needed.

I liked removing the repalloc calls inside this routine and did not think
it was worth optimizing. I am OK with reverting it back. Although v1
is incorrect since it's still initializing
NamedLWLockTrancheRequestArray to MAX_NAMED_TRANCHES
```

     if (NamedLWLockTrancheRequestArray == NULL)
     {
+        NamedLWLockTrancheRequestsAllocated = 16;
         NamedLWLockTrancheRequestArray = (NamedLWLockTrancheRequest *)
             MemoryContextAlloc(TopMemoryContext,
                                MAX_NAMED_TRANCHES
                                * sizeof(NamedLWLockTrancheRequest));
     }

```

instead of MAX_NAMED_TRANCHES, it should be
NamedLWLockTrancheRequestsAllocated .

Also, Previously NamedLWLockTrancheRequestsAllocated was global, but I don't
think it should ever be used outside of this function, so it's OK to declare it
as you have.

> Furthermore, the
> MAX_NAMED_TRANCHES check isn't actually needed because InitializeLWLocks()
> will do the same check via its calls to LWLockNewTrancheId() for all the
> named tranche requests.

I thought about that one and decided to add the error message there, since
requesting a tranche happens way before LWLockNewTrancheId is called
during CreateLWLocks, so it was more about erroring out slightly earlier.
But it may be ok to also just remove it.

--
Sami Imseih
Amazon Web Services (AWS)



Commits

  1. test_dsa: Avoid leaking LWLock tranches.

  2. Teach DSM registry to ERROR if attaching to an uninitialized entry.

  3. Add a test harness for the LWLock tranche code.

  4. Revert recent change to RequestNamedLWLockTranche().

  5. Move dynamically-allocated LWLock tranche names to shared memory.

  6. Prepare DSM registry for upcoming changes to LWLock tranche names.

  7. Add GetNamedDSA() and GetNamedDSHash().