Re: Bump soft open file limit (RLIMIT_NOFILE) to hard limit on startup

Поиск
Список
Период
Сортировка
Искать

Re: Bump soft open file limit (RLIMIT_NOFILE) to hard limit on startup

От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Jelte,

Haibo (cc'ed) and I reviewed this as part of a patch review workshop.

We agree with the basic policy Andres suggested: PostgreSQL should try to raise
the soft RLIMIT_NOFILE to cover the file descriptors already in use plus
max_files_per_process, rather than simply raising it to the hard limit.  The
current patch is generally moving in the right direction on that part.

Our main concern is the mechanism introduced to preserve the original limit for
external commands.  The patch adds its own pg_system()/pg_popen()
implementation based on fork(), performs PostgreSQL-specific work in the child,
restores the saved startup-time resource limit, adjusts signals and file
descriptors, and then calls exec().

This does not seem like a good long-term abstraction if we want to consider a
threaded PostgreSQL architecture.  In that architecture, backend sessions would
be threads in the same server process.  Forking such a process is fundamentally
different from fork_process() in today's process-per-backend architecture: only
the calling thread survives in the child, while locks held by other threads may
remain inherited.  The code between fork() and exec() therefore needs to be
extremely small and restricted to operations that are safe in this environment.

fork_process() is not really a counterexample.  It is infrastructure designed
specifically for PostgreSQL's current process architecture and will necessarily
have to be redesigned if backends become threads.  We should avoid introducing
new infrastructure today that carries the same assumption, particularly when
threading is itself being used as a motivation for the redesign.

The FD-limit policy and the external-process spawning mechanism also look like
two separate design questions.  Raising RLIMIT_NOFILE becomes even more useful
in a threaded architecture because client sockets, relation files, AIO
descriptors, etc. would all share one process-wide FD limit.  But that does not
imply that the current fork()-based pg_system()/pg_popen() design is suitable
for that architecture.

To make this forward-looking, a better direction would be a narrowly defined
process-spawning abstraction, using posix_spawn() where appropriate or a minimal
fork/exec implementation.  The child-side path should only perform the
operations strictly required before exec(), such as descriptor setup, signal
setup, and resource-limit adjustment, while allocation, logging, error handling,
and other PostgreSQL work remain in the parent.

So we support the basic RLIMIT_NOFILE policy change, but we are not convinced
that reimplementing system() and popen() this way is the right abstraction for it.

A few things from reading the patch:
1. Is there any supported way for a session to affect the soft limit after
startup, such as calling setrlimit() from a PL/pgSQL (or other procedural
language) function?  If the answer is "no", it would be good to state that
assumption explicitly.

2. In IncreaseOpenFileLimit(), rlim_cur + extra_files would overflow if rlim_cur
were RLIM_INFINITY, and Min() would then pick the wrapped value and lower the
limit drastically.  That is unreachable today, but only via the earlier
"rlim_cur == original_max_open_files.rlim_max" test combined with the
rlim_cur <= rlim_max guarantee.  A comment or an explicit RLIM_INFINITY check
would make it less fragile.

3. Nit: SaveOriginalOpenFileLimit() returns void, but its comment says "Returns
true if successful, false otherwise."

Regards,
Surya Poondla

Re: Bump soft open file limit (RLIMIT_NOFILE) to hard limit on startup

От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Jelte,

Apologies for the delay.
 
I agree with this. But I feel like that's exactly what this patchset
is currently doing. The newly introduced fork_for_shell_command makes
sure almost nothing is happening on the child-side of the fork. I
don't understand how the thing you describe differs from my currently
proposed implementation. Could you clarify?

I did some more digging and here is what I saw a place where it reaches indirectly:
pid = fork();
      if (pid == 0)
      {
          UseOriginalOpenFileLimit();
          pqsignal(SIGINT,  PG_SIG_DFL);
          ...
      }
 
UseOriginalOpenFileLimit() reports a setrlimit() failure with ereport(WARNING, (errmsg("setrlimit failed: %m"))). So the child body reads as four statements, but one of them enters the error-reporting subsystem: errstart() switches the current memory context to ErrorContext, errmsg() runs the format through dgettext() and builds the result with initStringInfo()/pstrdup(), and errfinish() emits it via EmitErrorReport() through the configured log destinations, which can include syslog(). That is what I meant by "PostgreSQL work in the child", and it is not visible at the call site.

I should also correct how I characterised fork_process() in my previous mail.
I set it aside as not being a counterexample, when it is actually the comparison that makes my point: its child-side body is limited to getpid(), getenv(), open(), write(), close() and a no-op init call. Not all of those are formally in POSIX's async-signal-safe set either, but none of them allocates, takes a lock, or enters a PostgreSQL subsystem. That property is what I care about, rather than list membership as such.

In the same spirit I should be upfront that setrlimit() is itself not in POSIX's async-signal-safe set. I don't think that is worth changing: it is a direct syscall in every libc we target, and takes no locks and allocates nothing. ereport() is a different category.

To be clear about why I think this is worth addressing even though it cannot deadlock on today's process-per-backend architecture:
- POSIX restricts what may be called between fork() and exec() in a process that has multiple threads, and ereport() is well outside that.
- We build against glibc, musl, macOS, the BSDs, Solaris and Windows, so I would rather not depend on any one of them being forgiving here.
- ereport() reaches our own subsystems, not just libc. Once backends are threads those acquire their own synchronization, and no libc behaviour helps with that.
- Keeping ereport() safe on this path in perpetuity, across future changes to elog.c, memory contexts, log destinations and translation, seems like an awkward invariant to have to maintain.

There is also a smaller present-day consequence: fork_for_shell_command() does not set MyProcPid the way fork_process() does, so if that ereport() ever fires the line is emitted with the parent's PID and session context attached, which would be misleading output.

To be clear, the WARNING in IncreaseOpenFileLimit() seems fine to me: that one runs during set_max_safe_fds() at startup, not in a child, and I take your earlier point that a failure there indicates a bug worth surfacing. It is only the copy reached from the child path that I am asking about.

So, concretely:
1. Report the setrlimit() failure from the parent, drop it, or emit it with a plain write(2), so that the child path contains only syscall-level work.
2. Add a comment on fork_for_shell_command() stating the constraint. This is new infrastructure that will have more additions, and the hazard is invisible from the call site.
3. In pg_popen()'s child, dup2()'s return value isn't checked. On failure the child would exec with the parent's descriptor still in place, so the
command's output would go elsewhere and the parent would see immediate EOF with no error.

I am no longer suggesting posix_spawn(), by the way: there is no standard way to set a resource limit through it, which is the whole point here. So a small fork/exec does look like the only workable approach, which is why the two items above are what I am asking for rather than a different abstraction.
 
Nothing is explicitly exposed to make it easy to do so, but changing
the soft limit after startup should not cause any problems (except
that if you lower it you can open fewer files ofcourse).


Maybe it is worth a comment then: max_safe_fds is computed once during startup, so a session that lowers rlim_cur afterwards leaves fd.c's accounting stale. Today that stays within one backend. Once backends are threads the limit is process-wide, so one session lowering it would affect every other session. 

Regards,
Surya Poondla

Re: Bump soft open file limit (RLIMIT_NOFILE) to hard limit on startup

От:
"Jelte Fennema-Nio" <postgres@jeltef.nl>
Дата:
Вложения:
On Wed, 16 Sept 2026 at 01:04, surya poondla  wrote:
> 1. Report the setrlimit() failure from the parent, drop it, or emit it with a plain write(2), so that the child path contains only syscall-level work.
> 2. Add a comment on fork_for_shell_command() stating the constraint. This is new infrastructure that will have more additions, and the hazard is invisible from the call site.
> 3. In pg_popen()'s child, dup2()'s return value isn't checked. On failure the child would exec with the parent's descriptor still in place, so the
> command's output would go elsewhere and the parent would see immediate EOF with no error.

I've addressed these three. see attached

Re: Bump soft open file limit (RLIMIT_NOFILE) to hard limit on startup

От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Jelte,

Thanks for v12. It addresses the three points from my last mail. I built it on current master and the basic behavior works, with ulimit -n 256 the postmaster logs "increased open file limit to 1003", and COPY FROM PROGRAM sees 256 again in the child.

I see two problems, though:
1. On macOS, startup can loop forever in count_usable_fds(). With the default unlimited hard limit, ulimit -n 256 and max_files_per_process=200000 (above kern.maxfilesperproc, 138240 here), the postmaster never finishes starting and logs "increased open file limit to ..." without end, each step adding 61763. setrlimit() accepts the value, but dup() still fails with EMFILE at kern.maxfilesperproc. The EMFILE branch calls IncreaseOpenFileLimit() again, which succeeds again, and we continue. Master starts fine in the same setup (max_safe_fds = 243). Perhaps retry on EMFILE only once after each successful increase, i.e. break if the next dup() still fails, and/or clamp to kern.maxfilesperproc.
2. pg_pclose() returns -1 without calling waitpid() when fclose() fails. One way to hit this is COPY TO PROGRAM where the program exits without reading its input. The fwrite() in CopySendEndOfRow() fails with EPIPE, and the code calls ClosePipeToProgram() to report the exit code. But fclose() then fails flushing the remaining buffered data, so the exit status is lost. COPY ... TO PROGRAM 'exit 3' reports on master:

      ERROR:  program "exit 3" failed
      DETAIL:  child process exited with exit code 3

  and on v12:

ERROR:  could not close pipe to external command: Broken pipe
The child is also never reaped, after two such COPYs in one session I see two <defunct> children of the backend, which remain until the backend exits (master leaves none). pclose() always waits for the child, so I think pg_pclose() should always call waitpid() and return the child's status.


A small observation, pipe2 is added to meson.build and pg_config.h.in, but not to configure.ac, so autoconf builds never define HAVE_PIPE2.

A few smaller things:
1. The IsOpenFileLimit() comment is cut off ("based on our. This should only be called if").
2. The new comment in 0002 is garbled ("if the result is different than what the used value turns out to be different than...").
3. SaveOriginalOpenFileLimit() still says "Returns true if successful", and the rlim_cur + extra_files overflow check from August isn't in yet.
4. In OpenPipeStream(), pqsignal(SIGPIPE, PG_SIG_IGN) after pg_popen() looks redundant now that the parent no longer sets SIGPIPE to SIG_DFL before forking.

Regards,
Surya Poondla
FAQ