Skip to content

Fix leaked thread stacks and lost child processes in the POSIX process wait thread - #260

Open
llucenic wants to merge 2 commits into
vibe-d:masterfrom
llucenic:fix-process-wait-thread
Open

llucenic wants to merge 2 commits into
vibe-d:masterfrom
llucenic:fix-process-wait-thread

Conversation

@llucenic

Copy link
Copy Markdown

Problem

PosixEventDriverProcesses starts a thread that waits for child processes whenever a process is added while no wait thread is running. The thread terminates as soon as waitid() reports ECHILD. This has two problems.

Leaked thread stacks. The terminated thread is never joined or detached. druntime's Thread destructor only calls pthread_detach() for a thread that is still registered, and a terminated thread has already been removed from the thread list. glibc therefore never frees its stack: per wait thread, 8 MiB of address space (the default ulimit -s), two memory mappings and the part of the stack the thread has used (8 kB of RSS per stack, read from /proc/self/smaps after 300 processes in a loop like the reproduction below). A program that runs one child process at a time, e.g. a web server that runs a converter per request, leaks one stack per process. With the default vm.max_map_count of 65530, thread creation fails after roughly 32,000 such processes (Thread.start() throws ThreadError). Before that, spawning a process gets slower and slower (see Measurements), as fork() has to copy all leaked mappings.

Lost child processes. If a process is added after waitid() has returned ECHILD, but before the wait thread has taken s_mutex, add() still sees s_waitThread set and does not start a new thread. The old thread then terminates and nobody waits for the new process. Its wait() callback only fires after some later process has been spawned. waitid() failing with EINTR had the same effect.

Reproduction

/+ dub.sdl:
	name "repro"
	dependency "eventcore" version="~>0.9.39"
+/
import core.time : Duration;
import eventcore.core;
import std.algorithm : count;
import std.file : readText;
import std.stdio : writefln;

void main()
{
	writefln("before: %s memory mappings", readText("/proc/self/maps").count('\n'));
	foreach (i; 0 .. 1000) {
		auto p = eventDriver.processes.spawn(["true"],
			ProcessStdinFile(ProcessRedirect.inherit),
			ProcessStdoutFile(ProcessRedirect.inherit),
			ProcessStderrFile(ProcessRedirect.inherit),
			null, ProcessConfig.none, null);
		bool done;
		eventDriver.processes.wait(p.pid, (ProcessID, int) nothrow { done = true; });
		while (!done) eventDriver.core.processEvents(Duration.max);
		eventDriver.processes.releaseRef(p.pid);
	}
	writefln("after 1000 processes: %s memory mappings", readText("/proc/self/maps").count('\n'));
}

On 0.9.39 (= current master), this prints 31 memory mappings before the loop and about 2,030 after it (the exact number varies by a few between runs). With this PR: 31 and 36.

Fix

  • Join in the next wait thread. A wait thread that terminates joins the previous, terminated one right before it terminates itself. Under s_mutex, it takes the previous thread from s_finishedWaitThread and stores itself there. At most one terminated wait thread stays unjoined at any time, and glibc reuses the stack of a joined thread for the next one.
    • Not in add(): the thread that spawns the process (usually an event loop) would block until the previous thread has finished terminating, including the TLS destructors of all modules.
    • Not handed to the new thread in a closure: the delegate of each Thread object would keep the previous one alive, and the whole chain would stay reachable from s_finishedWaitThread (about 270 bytes of GC heap per process).
    • Not a detached daemon thread: a daemon thread may still run after gc_term() at program exit and access the freed GC heap. A non-daemon thread also keeps the current behavior that the program waits for running child processes when it exits. Detaching a non-daemon thread does not work either, because thread_joinAll() would then try to join a detached thread.
  • Re-check under the lock on ECHILD. add() sets s_processAdded, and the wait thread resets it whenever it looks at s_processes. On ECHILD, the thread takes the lock and terminates only if no process has been added since. Otherwise it calls waitid() again.
  • Retry on EINTR.

Tests

  • tests/0-process-wait-thread.d: 200 sequential child processes must not add thread stacks or memory mappings (counted from /proc/self/maps, Linux only), and the GC heap in use after GC.collect() may grow by at most 64 bytes per process, so that terminated wait threads cannot stay reachable. Also checks that overlapping child processes are all waited for, that a child process spawned via std.process is left to its owner, and that the program terminates cleanly after its child processes have ended and while one is still running.
  • tests/0-process-race.d: a child process added between ECHILD and taking the lock must be waited for. To make this deterministic, version (EventcoreTestProcessRace), added in the test commit, makes the wait thread sleep 500 ms between the two, and the test checks that the delay was active. If you'd rather not have a test-only hook in the driver, I can drop it together with this test.

On master, both tests fail: 0-process-wait-thread with "Thread stacks of the process wait thread leak." (e.g. thread stacks 28 -> 228, memory mappings 93 -> 494), and 0-process-race, with the test hook added to master, with "Child process was not waited for (test hung)." after its 5 s timeout. With this PR both pass. Over 7 runs of the wait thread test (6 with epoll, 1 with select), thread stacks grew by +1 to +3, memory mappings by +3 or +4 and the GC heap by 128 bytes. The second child process of the race test is waited for after 400 ms. The race test passed 20 times in a row and 24 times with 8 copies running in parallel. Handing the previous thread over in a closure instead makes the GC heap check fail (GC heap 1,264 -> 55,792 bytes).

Run locally on Linux x86_64: run-ci.sh with epoll and select (DMD 2.107.1 and 2.098.1) and uring (DMD 2.098.1), and the process tests with DMD 2.096.0. With DMD 2.107.1, uring already fails on master, because dub treats the warnings about @system fields in uring.d and during as errors. Not run: LDC, DMD 2.087.1 and macOS. The new tests are skipped on Windows like issue-122-coalesced-sigchld.

Measurements

The loop from the reproduction above, one run on a 16-core Linux machine. The program calls GC.collect() once before the loop and again at each row, and averages the time per process over the last 100 processes. The first collection starts the GC's parallel marking threads, so their stacks are included in all rows, for master as well as for this PR.

processes master: mappings master: ms per process this PR: mappings this PR: ms per process
1,000 2,091 25.1 95 14.2
2,000 4,090 30.2 95 14.7
4,000 8,090 47.3 96 14.8
8,000 16,090 82.9 96 14.8

Both start with 90 mappings. The GC heap in use stays at 1,040 bytes (master) and 1,296 bytes (this PR) in all rows.

A vibe.d server application that runs wkhtmltopdf and xmllint per request, built against eventcore 0.9.29 with 440fc8e and an earlier revision of this patch, which handed the previous wait thread to the next one in a closure (see Fix). This does not affect the number of stacks and mappings:

before after
200 PDFs, 1 client +200 thread stacks, +403 mappings +0 stacks, +2 mappings
200 PDFs, 4 concurrent clients +4 stacks, +15 mappings +0 stacks, +9 mappings
200 XML validations, 1 client +200 stacks, +400 mappings +0 stacks, +0 mappings

Known limitations

These are not changed by this PR:

  • A process that is released (releaseRef() down to zero) before it has exited is removed from s_processes and never reaped. waitid(WNOWAIT) keeps reporting the zombie, so the wait thread spins and never sees ECHILD, and since it is a non-daemon thread, the program does not terminate. A child process that was spawned by other means and is never waited for by its owner has the same effect. This is a separate issue.
  • If Thread.start() fails in add(), the ThreadError passes through the nothrow function, DMD skips its scope (exit), and s_mutex stays locked. druntime does not recover from a failed start either: the thread stays in its list of threads about to start, and thread_joinAll() waits for it forever at program exit. This PR removes the leak that made this happen, but does not handle the error.
  • Theoretical double join at program exit: thread_joinAll() joins the previous wait thread if it is still running at that point. If another thread spawns a process at the same moment and the new wait thread runs to completion, both would join it. This requires spawning processes while the program terminates.

Ľudovít Lučenič and others added 2 commits October 19, 2026 21:25
The thread that waits for child processes is started when a process is
added while no wait thread is running, and it terminates as soon as
waitid() reports ECHILD. The terminated thread was neither joined nor
detached. druntime only detaches a thread in the Thread destructor if it
is still registered, which a terminated thread is not, so its stack was
never freed. Each wait thread leaked 8 MiB of address space (the default
stack size), two memory mappings and the stack memory it had touched. A
program that spawns one process at a time leaks one stack per process,
until thread creation fails at the vm.max_map_count limit.

- A wait thread that terminates now joins the previous, terminated one
  right before it terminates itself. Under s_mutex, it takes the previous
  thread from s_finishedWaitThread and stores itself there. The thread
  that spawns a process therefore never blocks on the termination of
  another thread, at most one terminated wait thread is left unjoined,
  and joined threads are not referenced anymore, so the GC can free
  their Thread objects.
- A process added after waitid() has returned ECHILD, but before the wait
  thread took the lock, was never waited for: add() saw the wait thread
  still registered and did not start a new one. The wait thread now
  terminates only if no process has been added since it last looked at
  the process list, and calls waitid() again otherwise.
- waitid() failing with EINTR terminated the thread like ECHILD. It is now
  retried.

The thread stays a non-daemon thread, so that the program still waits for
running child processes when it terminates. A daemon thread could access
the GC heap after gc_term().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- tests/0-process-wait-thread.d: 200 child processes run one after
  another must not leave thread stacks or memory mappings behind (checked
  via /proc/self/maps on Linux), and the terminated wait threads must not
  stay reachable (GC.stats().usedSize after GC.collect() may grow by at
  most 64 bytes per process). Overlapping child processes are all waited
  for, a child process spawned via std.process is left to its owner, and
  the program terminates cleanly both after its child processes have
  ended and while one is still running.
- tests/0-process-race.d: a child process that is added after the wait
  thread got ECHILD, but before it took the lock, must still be waited
  for. To make this deterministic, the test builds eventcore with the new
  version EventcoreTestProcessRace, which makes the wait thread sleep
  500 ms in that window, and checks that the delay was active. Other
  builds are not affected.

Both tests fail without the previous commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant