Repository navigation
Conversation
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
PosixEventDriverProcessesstarts a thread that waits for child processes whenever a process is added while no wait thread is running. The thread terminates as soon aswaitid()reportsECHILD. This has two problems.Leaked thread stacks. The terminated thread is never joined or detached. druntime's
Threaddestructor only callspthread_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 defaultulimit -s), two memory mappings and the part of the stack the thread has used (8 kB of RSS per stack, read from/proc/self/smapsafter 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 defaultvm.max_map_countof 65530, thread creation fails after roughly 32,000 such processes (Thread.start()throwsThreadError). Before that, spawning a process gets slower and slower (see Measurements), asfork()has to copy all leaked mappings.Lost child processes. If a process is added after
waitid()has returnedECHILD, but before the wait thread has takens_mutex,add()still seess_waitThreadset and does not start a new thread. The old thread then terminates and nobody waits for the new process. Itswait()callback only fires after some later process has been spawned.waitid()failing withEINTRhad the same effect.Reproduction
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
s_mutex, it takes the previous thread froms_finishedWaitThreadand 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.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.Threadobject would keep the previous one alive, and the whole chain would stay reachable froms_finishedWaitThread(about 270 bytes of GC heap per process).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, becausethread_joinAll()would then try to join a detached thread.ECHILD.add()setss_processAdded, and the wait thread resets it whenever it looks ats_processes. OnECHILD, the thread takes the lock and terminates only if no process has been added since. Otherwise it callswaitid()again.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 afterGC.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 viastd.processis 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 betweenECHILDand 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-threadwith "Thread stacks of the process wait thread leak." (e.g. thread stacks 28 -> 228, memory mappings 93 -> 494), and0-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 withepoll, 1 withselect), 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.shwithepollandselect(DMD 2.107.1 and 2.098.1) anduring(DMD 2.098.1), and the process tests with DMD 2.096.0. With DMD 2.107.1,uringalready fails on master, because dub treats the warnings about@systemfields inuring.dandduringas errors. Not run: LDC, DMD 2.087.1 and macOS. The new tests are skipped on Windows likeissue-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.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
wkhtmltopdfandxmllintper 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:Known limitations
These are not changed by this PR:
releaseRef()down to zero) before it has exited is removed froms_processesand never reaped.waitid(WNOWAIT)keeps reporting the zombie, so the wait thread spins and never seesECHILD, 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.Thread.start()fails inadd(), theThreadErrorpasses through thenothrowfunction, DMD skips itsscope (exit), ands_mutexstays locked. druntime does not recover from a failed start either: the thread stays in its list of threads about to start, andthread_joinAll()waits for it forever at program exit. This PR removes the leak that made this happen, but does not handle the error.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.