[Git][ghc/ghc][master] 2 commits: TimerManager: publish only evaluated timeout queues (#9809)
Marge Bot pushed to branch master at Glasgow Haskell Compiler / GHC Commits: adc294d0 by Erik de Castro Lopo at 2026-11-12T15:28:21-05:00 TimerManager: publish only evaluated timeout queues (#9809) The issue in #9809 was triggered by many threads registering timeouts at the same time and those timeouts being stored as unevaluated thunks in the shared list. When say 100,000 timeouts are registered at the same time, the program can be slowed down considerably and the memory usage grow unacceptably large. The commit that caused the problem was 2d5eccdf1c, a 2013 change that fixed #7653. The fix is to add a modifyTimeouts function which applies an edit to a copy of the list and fully evaluates the result before replacing the shared list with a CAS operation. Performance has improved for the threaded case and not regressed for the single thread case: Forked registrations of 100k timeouts (median of 5 runs): -N4: 0.577 s, 428 MB -> 0.078 s, 39 MB -N12: 1.227 s, 479 MB -> 0.127 s, 80 MB Forked registrations of 1M timeouts on -N1 (median of 3 and 10 runs): 5.21 s (range 0.67-9.47 s), 1613 MB -> 0.67 s, 250 MB Single-thread registrations are unchanged or slightly faster, and timer latency during registration storms improves (p99 lateness of a 1 ms threadDelay during 100k forked registrations on -N4: 302-394 ms -> 3.5-4.1 ms). The registration code still runs in constant stack, so #7653 stays fixed; T7653 and the concurrent, base and ghc-internal testsuites pass. modifyTimeouts is OPAQUE so that the optimiser cannot expose the edit function's inspection of the old queue next to the compare-and-swap and replace the expected pointer with the evaluated queue, which would make the compare-and-swap keep failing when the MutVar# holds a thunk or indirection. Regression test T9809.hs included. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> - - - - - b294b82f by Moritz Angermann at 2026-11-12T15:28:21-05:00 testsuite: give pause_resume_via_safe_ffi_concurrent 60s on Darwin CI The 10s System.Timeout watchdog was a false deadlock: five serialized 1s pauses plus rts_pause waiting on threadDelay/timer-manager traffic overruns that budget on loaded Mac runners. Keep a watchdog so a real hang still fails. - - - - - 7 changed files: - + changelog.d/T9809-timer-manager-contention - libraries/base/tests/.gitignore - + libraries/base/tests/T9809.hs - libraries/base/tests/all.T - libraries/ghc-internal/src/GHC/Internal/Event/TimerManager.hs - testsuite/tests/rts/pause-resume/all.T - testsuite/tests/rts/pause-resume/pause_resume_via_safe_ffi_concurrent.hs Changes: ===================================== changelog.d/T9809-timer-manager-contention ===================================== @@ -0,0 +1,12 @@ +section: ghc-internal +synopsis: Fix excessive GC, memory use and timer latency when many threads + register timeouts at once with ``threadDelay``, ``registerDelay`` or + ``System.Timeout.timeout``. +issues: #9809 +mrs: !16863 +description: { + Threads registering timeouts now publish only fully evaluated updates to + the timer manager's timeout queue, using a compare-and-swap loop, instead + of building chains of unevaluated updates that other threads then had to + evaluate or block on. +} ===================================== libraries/base/tests/.gitignore ===================================== @@ -275,4 +275,5 @@ /weak001 /T9395 /T9532 +/T9809 /T11555 ===================================== libraries/base/tests/T9809.hs ===================================== @@ -0,0 +1,29 @@ +-- #9809: when many threads registered timeouts at the same time, the +-- TimerManager published unevaluated timeout queues with atomicModifyIORef'. +-- The threads then built long chains of thunks and blocked on each other's +-- black holes, and the heap grew to hundreds of megabytes. all.T runs this +-- test with a heap limit that the old code exceeded. + +import Control.Concurrent +import Control.Monad +import Data.IORef +import GHC.Conc (TVar, atomically, newTVarIO, readTVar, registerDelay, retry, writeTVar) + +main :: IO () +main = do + let n = 100000 + ref <- newIORef [] + registered <- newTVarIO (0 :: Int) + replicateM_ n . forkIO $ do + tv <- registerDelay 10 + atomicModifyIORef' ref (\tvs -> (tv : tvs, ())) + atomically $ readTVar registered >>= writeTVar registered . (+ 1) + atomically $ do + r <- readTVar registered + when (r /= n) retry + readIORef ref >>= mapM_ waitFor + +-- | Block until a delay has fired, so that the test also checks that the +-- TimerManager fires every timeout. +waitFor :: TVar Bool -> IO () +waitFor tv = atomically $ readTVar tv >>= \fired -> unless fired retry ===================================== libraries/base/tests/all.T ===================================== @@ -193,6 +193,14 @@ test('T7653', [when(opsys('mingw32'), skip), omit_ways(prof_ways + ghci_ways)], compile_and_run, ['']) test('T7787', normal, compile_and_run, ['']) +# Before the fix for #9809 this needed more than 256MB of heap. +# Windows doesn't use TimerManager which makes the test ~80x slower +test('T9809', [when(opsys('mingw32'), skip), + req_ghc_smp, + req_target_smp, + only_ways(['threaded1', 'threaded2', 'nonmoving_thr'])], + compile_and_run, ['-threaded -with-rtsopts="-N2 -M128m"']) + test('topHandler01', [when(opsys('mingw32'), skip), js_broken(22261), req_process], compile_and_run, ['']) test('topHandler02', [when(opsys('mingw32'), skip), ===================================== libraries/ghc-internal/src/GHC/Internal/Event/TimerManager.hs ===================================== @@ -13,8 +13,10 @@ import GHC.Internal.Types () {-# LANGUAGE CPP #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE MagicHash #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE Trustworthy #-} +{-# LANGUAGE UnboxedTuples #-} -- TODO: use the new Windows IO manager module GHC.Internal.Event.TimerManager @@ -53,6 +55,9 @@ import GHC.Internal.Control.Exception (finally) import GHC.Internal.Data.Foldable (sequence_) import GHC.Internal.Data.IORef (IORef, atomicModifyIORef', mkWeakIORef, newIORef, readIORef, writeIORef) +import GHC.Internal.IORef (IORef(..)) +import GHC.Internal.Prim (casMutVar#, readMutVar#) +import GHC.Internal.STRef (STRef(..)) import GHC.Internal.Err (errorWithoutStackTrace) import GHC.Internal.Clock (getMonotonicTimeNSec) import GHC.Internal.Conc.Signal (runHandlers) @@ -188,6 +193,11 @@ step mgr = do -- Call all expired timer callbacks and return the time to the -- next timeout. + -- + -- This function uses atomicModifyIORef' whereas we use casMutVar# below + -- in modifyTimeouts. We deliberately avoid modifyTimeouts here + -- because this update is long, and with a CAS it would rarely win + -- against a stream of registrations, starving the manager. See #9809. mkTimeout :: IO Timeout mkTimeout = do now <- getMonotonicTimeNSec @@ -260,7 +270,7 @@ updateTimeout mgr (TK key) us = do editTimeouts :: TimerManager -> TimeoutEdit -> IO () editTimeouts mgr g = do - wake <- atomicModifyIORef' (emTimeouts mgr) f + wake <- modifyTimeouts (emTimeouts mgr) f when wake (wakeManager mgr) where f q = (q', wake) @@ -276,4 +286,35 @@ editTimeouts mgr g = do t0 /= t1 _ -> True +-- The issue in #9809 was that for the threaded runtime (where each process +-- has its own timer manager), timer events added to the shared list of +-- events were potentially added unevaluated. When many threads (eg 100,000) +-- add entries at the same time, the program can slow down considerably and +-- use significant amounts of memory. The crux of the matter was that each +-- thread updated the shared list lazily. In this case it's easy to build a +-- massive list of unevaluated thunks. +-- +-- The solution is for each thread that wants to update the shared list to +-- apply its edit to a copy of the list and fully evaluate the result before +-- replacing the shared list. Updating the list is an O(log n) process and it +-- runs in constant stack space, see #7653. The old list is replaced by the +-- new list using a compare-and-swap (CAS) operation (which compares machine +-- level pointers). If the CAS fails (ie the list has been updated by another +-- thread) it starts again with the new list created by the other thread. + +-- NOINLINE could have been used here but OPAQUE has stronger guarantees +-- (ie worker/wrapper optimisation is prevented). If this function were +-- inlined above (possible without either pragma), the CAS operation may end up +-- comparing with a different pointer to the one it read (eg if GHC replaces a +-- thunk or indirection with the evaluated value). +{-# OPAQUE modifyTimeouts #-} +modifyTimeouts :: IORef TimeoutQueue -> (TimeoutQueue -> (TimeoutQueue, b)) -> IO b +modifyTimeouts (IORef (STRef ref)) f = IO modLoop + where + modLoop s0 = case readMutVar# ref s0 of + (# s1, oldVar #) -> case f oldVar of + (newVar, r) -> newVar `seq` case casMutVar# ref oldVar newVar s1 of + (# s2, 0#, _ #) -> (# s2, r #) + (# s2, _, _ #) -> modLoop s2 + #endif ===================================== testsuite/tests/rts/pause-resume/all.T ===================================== @@ -14,6 +14,8 @@ test('pause_resume_via_safe_ffi_concurrent', [ only_ways(['threaded1', 'threaded2']) , req_c , extra_files(['pause_resume.c','pause_resume.h']) + # Internal watchdog is 60s; give the harness room on loaded Darwin CI. + , run_timeout_multiplier(2) ], multi_compile_and_run, ['pause_resume_via_safe_ffi_concurrent', [('pause_resume.c','')], '']) test('pause_and_use_rts_api', ===================================== testsuite/tests/rts/pause-resume/pause_resume_via_safe_ffi_concurrent.hs ===================================== @@ -8,6 +8,7 @@ import Foreign.Marshal.Alloc import Foreign.Ptr import Foreign.Storable import System.Exit +import System.IO (hFlush, stdout) import System.Timeout foreign import ccall safe "pause_resume.h pauseAndResume" @@ -38,11 +39,17 @@ main = do countPtr putMVar mvar () - -- Wait (at least 2n seconds to be safe) for all threads to finish. - result <- timeout (2 * n * 1000000) (mapM_ takeMVar mvars) + -- Each pause holds the RTS for about a second, so n concurrent + -- calls serialize to ~n seconds. 2n (10s) was enough on Linux but + -- a false deadlock on Darwin CI: rts_pause waits for every + -- capability, and the counter threads keep hitting the timer + -- manager via threadDelay. Keep a watchdog so a real hang still + -- fails, but give 60s of slack. + result <- timeout (60 * 1000000) (mapM_ takeMVar mvars) case result of Nothing -> do putStrLn "Not all rts_pause/rts_resume threads have finished. Assuming deadlocked and failing test." + hFlush stdout exitFailure Just () -> do putStrLn "All threads finished" View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/419f2a12d2f7a0b59b3a7e79ae26b2a... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/419f2a12d2f7a0b59b3a7e79ae26b2a... You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
participants (1)
-
Marge Bot (@marge-bot)