diff --git a/io-sim/CHANGELOG.md b/io-sim/CHANGELOG.md index 9ceebad0..18b54680 100644 --- a/io-sim/CHANGELOG.md +++ b/io-sim/CHANGELOG.md @@ -14,6 +14,39 @@ * Fixed `timeout` in `IOSim` and `IOSimPOR`: if the action finished when the timeout fired, the timeout exception could be raised after `timeout` returned (#269). +* Masking state is correctly restored after an async exception (both IOSim and IOSimPOR). +* A thread blocked in `throwTo` which is interrupted, e.g. by `killThread`, + cancels its `throwTo`, as in GHC (both `IOSim` and `IOSimPOR`). Before, + the target still received the exception when it unmasked, and the + interrupted thread was woken up then, even out of an unrelated blocking + call. +* A `throwTo` which blocks is an interruptible point, as in GHC: if the + thread has pending async exceptions, and is not `MaskedUninterruptible`, + one of them is raised, and the target does not receive the exception (both + `IOSim` and `IOSimPOR`). +* A `throwTo` no longer replaces an async exception which was raised in its + target, but which the target has not run yet: + `throwTo tid e1 >> throwTo tid e2` raised only `e2`. The second `throwTo` + now blocks until the target can receive it, as in GHC (both `IOSim` and + `IOSimPOR`). In `IOSim`, when nested `timeout`s fire at the same time, the + outer one now wins. +* `IOSimPOR`: `cancelTimeout`, and the cancel action returned by + `registerDelayCancellable`, only wake up threads blocked in STM, as in + `IOSim`. Before, they also woke up a thread which had waited for the + timeout in an STM transaction, but was blocked in something else by then, + e.g. in a `throwTo`, which then returned before the exception was + delivered. +* `IOSimPOR`: the threads which `timeout` forks to throw its exception are + racy if the timed thread is, as other threads forked by a racy thread are: + races with their steps are explored, and traces show them as + `RacyThreadId`s. In a thread which called `exploreRaces`, e.g. the main + thread, they now have a lower priority than the timed thread, so the + default schedule can end differently when the action finishes at the same + time as the timeout fires. +* `IOSimPOR` explores the race between a `throwTo` and a step which wakes up + its target, e.g. by writing a `TVar` the target is blocked on. This can + multiply the number of explored schedules, e.g. when timeouts fire while + their actions wait in STM transactions which other threads wake up. ## 1.11.0.0 diff --git a/io-sim/io-sim.cabal b/io-sim/io-sim.cabal index ad0e6228..450459d4 100644 --- a/io-sim/io-sim.cabal +++ b/io-sim/io-sim.cabal @@ -76,7 +76,7 @@ library psqueues >=0.2 && <0.3, time >=1.9.1 && <1.16, quiet, - QuickCheck, + QuickCheck >=2.15, parallel @@ -93,6 +93,7 @@ test-suite test Test.Control.Monad.STM Test.Control.Monad.Utils Test.Control.Monad.IOSim + Test.Control.Monad.IOSim.Preemption Test.Control.Monad.IOSimPOR default-language: GHC2021 default-extensions: LambdaCase diff --git a/io-sim/src/Control/Monad/IOSim.hs b/io-sim/src/Control/Monad/IOSim.hs index 53f9ad59..6a114a7e 100644 --- a/io-sim/src/Control/Monad/IOSim.hs +++ b/io-sim/src/Control/Monad/IOSim.hs @@ -13,6 +13,16 @@ module Control.Monad.IOSim , Failure (..) , runSimTrace , runSimTraceST + -- *** Preemption + -- $preemption + , Preemption (..) + , noPreemption + , preemptRandom + , preemptFromMap + , preemptionsOf + , runSimWith + , runSimTraceWith + , runSimTraceSTWith -- *** QuickCheck Monadic combinators , monadicIOSim_ , monadicIOSim @@ -97,6 +107,8 @@ import Prelude import Data.Bifoldable import Data.Dynamic (fromDynamic) import Data.List (intercalate) +import Data.Map.Strict (Map) +import Data.Map.Strict qualified as Map import Data.Set (Set) import Data.Set qualified as Set import Data.Typeable (Typeable) @@ -109,7 +121,9 @@ import Control.Monad.ST.Lazy import Control.Monad.Class.MonadThrow as MonadThrow -import Control.Monad.IOSim.Internal (runSimTraceST) +import Control.Monad.Class.MonadTime.SI (DiffTime) +import Control.Monad.IOSim.Internal (Preemption (..), noPreemption, + preemptRandom, runSimTraceST, runSimTraceSTWith) import Control.Monad.IOSim.Types import Control.Monad.IOSimPOR.Internal qualified as IOSimPOR (controlSimTraceST) import Control.Monad.IOSimPOR.QuickCheckUtils @@ -502,6 +516,49 @@ ppSayTrace tr = ppEvents runSimTrace :: forall a. (forall s. IOSim s a) -> SimTrace a runSimTrace mainAction = runST (runSimTraceST mainAction) +-- +-- Preemption +-- + +-- $preemption +-- +-- /IOSim/ advances time only when no thread can run, so a window between two +-- steps of one thread is never open while time passes. Real threads are +-- descheduled at any point. A 'Preemption' oracle restores some of that: at +-- a thread's yield points (after a committed STM transaction, `yield`, or +-- `timeout`'s setup) it may deschedule the thread for a while. Other threads +-- run and time advances; the preempted thread then carries on. Without an +-- oracle ('runSimTrace') nothing changes. +-- +-- Search with 'preemptRandom', take the preemptions of a failing run with +-- 'preemptionsOf', and shrink them as a 'Map' replayed by 'preemptFromMap'. + +-- | Preempt exactly the given (thread, yield count) points. +-- +preemptFromMap :: Map (IOSimThreadId, Int) DiffTime -> Preemption +preemptFromMap m = Preemption $ \tid n -> Map.lookup (tid, n) m + +-- | The preemptions a run made, for 'preemptFromMap'. +-- +preemptionsOf :: SimTrace a -> Map (IOSimThreadId, Int) DiffTime +preemptionsOf = Map.fromList . go + where + go (SimTrace _ tid _ (EventPreempted _ n d _) t) = ((tid, n), d) : go t + go (Cons _ t) = go t + go (Nil _) = [] + +-- | 'runSimTrace' with a preemption oracle. +-- +runSimTraceWith :: forall a. Preemption -> (forall s. IOSim s a) -> SimTrace a +runSimTraceWith preemption mainAction = + runST (runSimTraceSTWith preemption mainAction) + +-- | 'runSim' with a preemption oracle. +-- +runSimWith :: forall a. Preemption -> (forall s. IOSim s a) -> Either Failure a +runSimWith preemption mainAction = + traceResult False (runSimTraceWith preemption mainAction) + -- -- IOSimPOR -- @@ -562,8 +619,8 @@ exploreSimTrace optsf mainAction k = $ controlSimTrace (explorationStepTimelimit opts) control mainAction (sleeper,trace) = compareTraces passingTrace trace0 - in ( counterexample ("Schedule control: " ++ show control) - $ counterexample + in counterexample ("Schedule control: " ++ show control) + ( counterexample (case sleeper of Nothing -> "No thread delayed" Just ((t,tid,lab),racing) -> @@ -575,7 +632,9 @@ exploreSimTrace optsf mainAction k = ) $ k passingTrace trace ) - .&&| let limit = (n+m-1) `div` m + -- `.&&.` must be sequential: the second property does `readRaces`, + -- which will only be populated when the first property is evaluated. + .&&. let limit = (n+m-1) `div` m -- To ensure the set of schedules explored is deterministic, we -- filter out cached ones *after* selecting the children of this -- node. diff --git a/io-sim/src/Control/Monad/IOSim/CommonTypes.hs b/io-sim/src/Control/Monad/IOSim/CommonTypes.hs index 31dd4bf3..d148a0a5 100644 --- a/io-sim/src/Control/Monad/IOSim/CommonTypes.hs +++ b/io-sim/src/Control/Monad/IOSim/CommonTypes.hs @@ -11,7 +11,6 @@ module Control.Monad.IOSim.CommonTypes , StepId , ppStepId , childThreadId - , setRacyThread , TVarId (..) , VarId , TimeoutId (..) @@ -74,13 +73,10 @@ ppIOSimThreadId :: IOSimThreadId -> String ppIOSimThreadId (RacyThreadId as) = "Thread {"++ intercalate "," (map show as) ++"}" ppIOSimThreadId (ThreadId as) = "Thread " ++ show as -childThreadId :: IOSimThreadId -> Int -> IOSimThreadId -childThreadId (RacyThreadId is) i = RacyThreadId (is ++ [i]) -childThreadId (ThreadId is) i = ThreadId (is ++ [i]) - -setRacyThread :: IOSimThreadId -> IOSimThreadId -setRacyThread (ThreadId is) = RacyThreadId is -setRacyThread tid@RacyThreadId{} = tid +childThreadId :: Bool -> IOSimThreadId -> Int -> IOSimThreadId +childThreadId _ (RacyThreadId is) i = RacyThreadId (is ++ [i]) +childThreadId False (ThreadId is) i = ThreadId (is ++ [i]) +childThreadId True (ThreadId is) i = RacyThreadId (is ++ [i]) -- | Execution step in `IOSimPOR` is identified by the thread id and -- a monotonically increasing number (thread specific). @@ -187,6 +183,9 @@ data ThreadStatus = ThreadRunning data BlockedReason = BlockedOnSTM | BlockedOnDelay | BlockedOnThrowTo + | BlockedOnPreempt + -- ^ descheduled by the preemption oracle while runnable; + -- not an interruptible operation deriving (Eq, Show) -- | A labelled value. diff --git a/io-sim/src/Control/Monad/IOSim/Internal.hs b/io-sim/src/Control/Monad/IOSim/Internal.hs index 2c482a39..219ef4e8 100644 --- a/io-sim/src/Control/Monad/IOSim/Internal.hs +++ b/io-sim/src/Control/Monad/IOSim/Internal.hs @@ -14,6 +14,10 @@ module Control.Monad.IOSim.Internal ( IOSim (..) , runIOSim , runSimTraceST + , runSimTraceSTWith + , Preemption (..) + , noPreemption + , preemptRandom , traceM , traceSTM , STM @@ -45,6 +49,7 @@ import Data.Deque.Strict (Deque) import Data.Deque.Strict qualified as Deque import Data.Dynamic import Data.Foldable (foldlM, toList, traverse_) +import Data.Hashable (hashWithSalt) import Data.IntPSQ (IntPSQ) import Data.IntPSQ qualified as PSQ import Data.List qualified as List @@ -55,6 +60,10 @@ import Data.Maybe (catMaybes, mapMaybe) import Data.Set (Set) import Data.Set qualified as Set import Data.Time (UTCTime (..), fromGregorian) +import Data.Time.Clock (diffTimeToPicoseconds, picosecondsToDiffTime) +import System.Environment (lookupEnv) +import System.IO.Unsafe (unsafePerformIO) +import Text.Read qualified as TR import Control.Exception (NonTermination (..), SomeAsyncException, assert, throw) @@ -70,7 +79,7 @@ import Control.Monad.Class.MonadSTM hiding (STM) import Control.Monad.Class.MonadSTM.Internal (TMVarDefault (TMVar)) import Control.Monad.Class.MonadThrow hiding (getMaskingState) import Control.Monad.Class.MonadTime -import Control.Monad.Class.MonadTimer.SI (TimeoutState (..)) +import Control.Monad.Class.MonadTimer.SI (DiffTime, TimeoutState (..)) import Control.Monad.IOSim.InternalTypes import Control.Monad.IOSim.Types hiding (SimEvent (SimPOREvent), @@ -126,6 +135,55 @@ data TimerCompletionInfo s = | TimerTimeout !IOSimThreadId !TimeoutId !(TMVar (IOSim s) IOSimThreadId) -- ^ `timeout` timer run by `IOSimThreadId` which was assigned the given -- `TimeoutId` (only used to report in a trace). + | TimerPreempt !IOSimThreadId !TimeoutId + -- ^ end of a preemption of `IOSimThreadId` (see 'Preemption'). + + +-- | A preemption oracle. At each yield point of a thread (after a committed +-- STM transaction, `yield`, or `timeout`'s setup) it is asked with the thread +-- and the number of yield points that thread passed before this one. When +-- it returns a positive delay the thread is descheduled for that long, while +-- it is runnable: other threads run and time advances. The thread is not +-- interruptible while preempted unless it is unmasked. +-- +newtype Preemption = Preemption { + preemptAt :: IOSimThreadId -> Int -> Maybe DiffTime + } + +noPreemption :: Preemption +noPreemption = Preemption (\_ _ -> Nothing) + +-- | Preempt each yield point with probability @p@, for a delay drawn +-- uniformly from @(0, maxDelay]@ in microsecond steps. The choice is a pure +-- function of the seed, the thread and its yield count. +-- +preemptRandom :: Int -- ^ seed + -> Double -- ^ probability + -> DiffTime -- ^ maximal delay + -> Preemption +preemptRandom seed p maxDelay = Preemption $ \tid n -> + let h1 = hashWithSalt seed (tid, n, False) `mod` 1_000_000 + h2 = hashWithSalt seed (tid, n, True) + us = max 1 (diffTimeToPicoseconds maxDelay `div` 1_000_000) + in if fromIntegral h1 < p * 1_000_000 + then Just (picosecondsToDiffTime ((1 + toInteger h2 `mod` us) * 1_000_000)) + else Nothing + +-- | PROTOTYPE ONLY, for surveying existing test suites: when the environment +-- variable @IOSIM_PREEMPT=p,maxDelayMicroseconds,seed@ is set, every +-- 'runSimTraceST' (and so 'runSim', 'runSimTrace', ...) uses 'preemptRandom' +-- with those parameters. +envPreemption :: Preemption +envPreemption = unsafePerformIO $ do + v <- lookupEnv "IOSIM_PREEMPT" + pure $ case fmap (splitOn ',') v of + Just [p, us, seed] -> preemptRandom (TR.read seed) (TR.read p) (fromIntegral (TR.read us :: Int) / 1_000_000) + _ -> noPreemption + where + splitOn c xs = case break (== c) xs of + (a, []) -> [a] + (a, _ : b) -> a : splitOn c b +{-# NOINLINE envPreemption #-} type Timeouts s = IntPSQ Time (TimerCompletionInfo s) @@ -133,19 +191,24 @@ type Timeouts s = IntPSQ Time (TimerCompletionInfo s) -- | Internal state. -- data SimState s a = SimState { - runqueue :: !(Deque IOSimThreadId), + runqueue :: !(Deque IOSimThreadId), -- | All threads other than the currently running thread: both running -- and blocked threads. - threads :: !(Map IOSimThreadId (Thread s a)), + threads :: !(Map IOSimThreadId (Thread s a)), -- | current time - curTime :: !Time, + curTime :: !Time, -- | ordered list of timers and timeouts - timers :: !(Timeouts s), + timers :: !(Timeouts s), -- | list of clocks - clocks :: !(Map ClockId UTCTime), - nextVid :: !VarId, -- ^ next unused 'VarId' - nextTmid :: !TimeoutId, -- ^ next unused 'TimeoutId' - nextUniq :: !(Unique s) -- ^ next unused @'Unique' s@ + clocks :: !(Map ClockId UTCTime), + nextVid :: !VarId, -- ^ next unused 'VarId' + nextTmid :: !TimeoutId, -- ^ next unused 'TimeoutId' + nextUniq :: !(Unique s), -- ^ next unused @'Unique' s@ + preemption :: !Preemption, + -- | yield points each thread passed + yieldCount :: !(Map IOSimThreadId Int), + -- | the current preemption of each preempted thread + preempted :: !(Map IOSimThreadId TimeoutId) } initialState :: SimState s a @@ -158,7 +221,10 @@ initialState = clocks = Map.singleton (ClockId []) epoch1970, nextVid = 0, nextTmid = TimeoutId 0, - nextUniq = MkUnique 0 + nextUniq = MkUnique 0, + preemption = noPreemption, + yieldCount = Map.empty, + preempted = Map.empty } where epoch1970 = UTCTime (fromGregorian 1970 1 1) 0 @@ -243,6 +309,10 @@ schedule !thread@Thread{ maybe (unsafeUnregisterTimeout tmid) killThread <$> closeTimeoutLock (TimeoutLock tmid lock) + -- If the assassin has already thrown, but we were not + -- interruptible, its exception is pending. `cleanup` kills the + -- assassin, which cancels its `throwTo` and retracts the pending + -- exception (see `dropThrowToFrom`). let thread' = thread { threadControl = ThreadControl (unIOSim cleanup (\() -> k (Just x))) @@ -259,17 +329,41 @@ schedule !thread@Thread{ -- Found a CatchFrame (Right thread'@Thread { threadControl = ThreadControl handlerAction handlerCtl , threadMasking = maskst' + , threadThrowTo }, timers'', locks) -> do -- We found a suitable exception handler, continue with that, - -- but first cleanup any unwind `TimeoutFrame` locks + -- but first cleanup all unwound `TimeoutFrame`s. tids <- catMaybes <$> traverse closeTimeoutLock locks - let cleanups = traverse_ killThread tids - trace <- schedule thread' { - threadControl = - ThreadControl (case cleanups of - IOSim k' -> k' (\() -> handlerAction)) - handlerCtl - } + let -- NOTE: we could always run the cleanups within + -- `uninterruptibleMask_` (as GHC's `cleanupTimeout` does). We + -- only wrap it when it matters for performance reasons. + -- + -- When the wrapped cleanups end, the thread unmasks back to + -- `maskst'`, which raises a pending async exception if the thread + -- is `Unmasked`. + cleanups :: IOSim s () + cleanups = + case maskst' of + -- the thread is not blocked, thus it is interruptible iff it is + -- `Unmasked` + Unmasked + -- there are pending async exceptions: don't raise any of + -- them until cleanup ends + | not (null threadThrowTo) + -> uninterruptibleMask_ (traverse_ killThread tids) + + -- otherwise the thread is either masked or there are no + -- pending async exceptions, so none of the cleanups will be + -- interrupted, since they neither block nor yield (the + -- assassin threads are never masked, so `killThread` from + -- any of the cleanups is non-blocking). This holds even if + -- an assassin won the race, unlike in `IOSimPOR`, where + -- `killThread` yields. + _ -> traverse_ killThread tids + trace <- schedule thread' { threadControl = + ThreadControl (unIOSim cleanups (\() -> handlerAction)) + handlerCtl + } simstate { timers = timers'' } return (SimTrace time tid tlbl (EventThrow e) $ SimTrace time tid tlbl (EventMask maskst') trace) @@ -480,7 +574,7 @@ schedule !thread@Thread{ Fork a k -> do let !nextId = threadNextTId thread - !tid' = childThreadId tid nextId + !tid' = childThreadId False tid nextId !thread' = thread { threadControl = ThreadControl (k tid') ctl , threadNextTId = succ nextId } !thread'' = Thread { threadId = tid' @@ -600,16 +694,24 @@ schedule !thread@Thread{ Just t -> not (threadInterruptible t) _ -> False if willBlock - then do - -- The target thread has async exceptions masked so we add the - -- exception and the source thread id to the pending async exceptions. - let adjustTarget t = t { threadThrowTo = (e, Labelled tid tlbl) : threadThrowTo t } - threads' = Map.adjust adjustTarget tid' threads - !trace <- deschedule (Blocked BlockedOnThrowTo) thread' simstate { threads = threads' } - return $ SimTrace time tid tlbl (EventThrowTo e tid') - $ SimTrace time tid tlbl EventThrowToBlocked - $ SimTrace time tid tlbl (EventDeschedule (Blocked BlockedOnThrowTo)) - $ trace + then case threadThrowTo thread of + -- `throwTo` blocks, which is an interruptible point: if we have + -- pending async exceptions, and are not `MaskedUninterruptible`, one + -- of them is raised instead, and `e` is neither thrown nor traced. + _ : _ | maskst /= MaskedUninterruptible -> do + !trace <- schedulePendingThrowTo thread' simstate + return $ SimTrace time tid tlbl (EventDeschedule Interruptable) + $ trace + _ -> do + -- The target thread has async exceptions masked so we add the + -- exception and the source thread id to the pending async exceptions. + let adjustTarget t = t { threadThrowTo = (e, Labelled tid tlbl) : threadThrowTo t } + threads' = Map.adjust adjustTarget tid' threads + !trace <- deschedule (Blocked BlockedOnThrowTo) thread' simstate { threads = threads' } + return $ SimTrace time tid tlbl (EventThrowTo e tid') + $ SimTrace time tid tlbl EventThrowToBlocked + $ SimTrace time tid tlbl (EventDeschedule (Blocked BlockedOnThrowTo)) + $ trace else do -- The target thread has async exceptions unmasked, or is masked but -- is blocked (and all blocking operations are interruptible) then we @@ -619,16 +721,42 @@ schedule !thread@Thread{ -- be resolved if the thread terminates or if it leaves the exception -- handler (when restoring the masking state would trigger the any -- new pending async exception). - let adjustTarget t@Thread{ threadControl = ThreadControl _ ctl' } = - t { threadControl = ThreadControl (Throw e) ctl' + -- + -- If the target thread is blocked in `throwTo`, interrupting it + -- cancels its `throwTo`: we drop its exception from the pending async + -- exceptions of its target, which might be this thread. + -- + -- The target thread is also `MaskedInterruptible`, to make + -- subsequent `throwTo` to that thread blocking, otherwise they will + -- again land in this branch and overwrite a pending throw. When the + -- `e` is thrown, the masking state is restored. + let adjustTarget :: Thread s a -> Thread s a + adjustTarget t@Thread{ threadControl = ThreadControl _ ctl', + threadMasking = maskst' } = + t { threadControl = ThreadControl (Throw e) + (MaskFrame Return maskst' ctl') + , threadMasking = MaskedInterruptible , threadStatus = ThreadRunning } + + cancelThrowTo :: Bool + cancelThrowTo = case Map.lookup tid' threads of + Just Thread { threadStatus = ThreadBlocked BlockedOnThrowTo } + -> True + _ -> False + + thread'' + | cancelThrowTo = dropThrowToFrom tid' thread' + | otherwise = thread' + simstate0 + | cancelThrowTo = simstate { threads = Map.map (dropThrowToFrom tid') threads } + | otherwise = simstate simstate'@SimState { threads = threads' } - = snd (unblockThreads False [tid'] simstate) + = snd (unblockThreads False [tid'] (cancelPreemption tid' simstate0)) threads'' = Map.adjust adjustTarget tid' threads' simstate'' = simstate' { threads = threads'' } - trace <- schedule thread' simstate'' + trace <- schedule thread'' simstate'' return $ SimTrace time tid tlbl (EventThrowTo e tid') $ trace @@ -659,50 +787,42 @@ schedule !thread@Thread{ threadInterruptible :: Thread s a -> Bool threadInterruptible thread = case threadMasking thread of - Unmasked -> True - -- blocking operations are interruptible - MaskedInterruptible -> isThreadBlocked thread - MaskedUninterruptible -> False + Unmasked -> True + MaskedInterruptible + | ThreadBlocked BlockedOnPreempt <- threadStatus thread + -> False -- preemption is not an operation + | isThreadBlocked thread -> True -- blocking operations are interruptible + | otherwise -> False + MaskedUninterruptible -> False deschedule :: Deschedule -> Thread s a -> SimState s a -> ST s (SimTrace a) -deschedule Yield !thread !simstate@SimState{runqueue, threads} = - - -- We don't interrupt runnable threads to provide fairness anywhere else. - -- We do it here by putting the thread to the back of the runqueue, behind - -- all other runnable threads. - -- - -- For testing, we should have a more sophisticated policy to show that - -- algorithms are not sensitive to the exact policy, so long as it is a - -- fair policy (all runnable threads eventually run). - - let runqueue' = Deque.snoc (threadId thread) runqueue - threads' = Map.insert (threadId thread) thread threads in - reschedule simstate { runqueue = runqueue', threads = threads' } - -deschedule Interruptable !thread@Thread { - threadId = tid, - threadControl = ThreadControl _ ctl, - threadMasking = Unmasked, - threadThrowTo = (e, tid') : etids, - threadLabel = tlbl - } - !simstate@SimState{ curTime = time, threads } = +deschedule Yield !thread@Thread{ threadId = tid, threadLabel = tlbl } + !simstate@SimState{ curTime = time, timers, nextTmid, threads, + preemption, yieldCount, preempted } + | Just d <- preemptAt preemption tid n + , d > 0 = + let !expiry = d `addTime` time + !thread' = thread { threadStatus = ThreadBlocked BlockedOnPreempt } + !timers' = PSQ.insert (coerce nextTmid) expiry + (TimerPreempt tid nextTmid) timers + in SimTrace time tid tlbl (EventPreempted nextTmid n d expiry) <$> + reschedule simstate { threads = Map.insert tid thread' threads, + timers = timers', + nextTmid = succ nextTmid, + yieldCount = yieldCount', + preempted = Map.insert tid nextTmid preempted } + | otherwise = + yieldThread thread simstate { yieldCount = yieldCount' } + where + !n = Map.findWithDefault 0 tid yieldCount + !yieldCount' = Map.insert tid (succ n) yieldCount +deschedule Interruptable !thread@Thread { threadMasking = Unmasked + , threadThrowTo = _ : _ } !simstate = -- We're unmasking, but there are pending blocked async exceptions. -- So immediately raise the exception and unblock the blocked thread -- if possible. - let thread' = thread { threadControl = ThreadControl (Throw e) ctl - , threadMasking = MaskedInterruptible - , threadThrowTo = etids } - (unblocked, - simstate') = unblockThreads False [l_labelled tid'] simstate - in do - trace <- schedule thread' simstate' - return $ SimTrace time tid tlbl (EventThrowToUnmasked tid') - $ traceMany [ (time, tid'', tlbl'', EventThrowToWakeup) - | tid'' <- unblocked - , let tlbl'' = lookupThreadLabel tid'' threads ] - trace + schedulePendingThrowTo thread simstate deschedule Interruptable !thread !simstate = -- Either masked or unmasked but no pending async exceptions. @@ -716,19 +836,20 @@ deschedule (Blocked _blockedReason) !thread@Thread { threadThrowTo = _ : _ -- we have async exceptions masked, and there are pending blocked async -- exceptions. So immediately raise the exception and unblock the blocked -- thread if possible. - deschedule Interruptable thread { threadMasking = Unmasked } simstate + schedulePendingThrowTo thread simstate deschedule (Blocked blockedReason) !thread !simstate@SimState{threads} = let thread' = thread { threadStatus = ThreadBlocked blockedReason } threads' = Map.insert (threadId thread') thread' threads in reschedule simstate { threads = threads' } -deschedule Terminated !thread !simstate@SimState{ curTime = time, threads } = +deschedule Terminated !thread !simstate@SimState{ curTime = time, threads, yieldCount } = -- This thread is done. If there are other threads blocked in a -- ThrowTo targeted at this thread then we can wake them up now. let !wakeup = map (l_labelled . snd) (reverse (threadThrowTo thread)) (unblocked, - !simstate') = unblockThreads False wakeup simstate + !simstate') = unblockThreads False wakeup + simstate { yieldCount = Map.delete (threadId thread) yieldCount } in do !trace <- reschedule simstate' return $ traceMany @@ -740,6 +861,65 @@ deschedule Terminated !thread !simstate@SimState{ curTime = time, threads } = deschedule Sleep _thread _simstate = error "IOSim: impossible happend" +-- | Raise the first pending async exception of a thread, and unblock the +-- thread which threw it. +-- +schedulePendingThrowTo :: Thread s a + -> SimState s a + -> ST s (SimTrace a) +schedulePendingThrowTo !thread@Thread { + threadId = tid, + threadControl = ThreadControl _ ctl, + threadThrowTo = (e, tid') : etids, + threadLabel = tlbl + } + !simstate@SimState{ curTime = time, threads } = + -- Unlike in `IOSimPOR` case, we don't need to set masking state and add + -- a `MaskFrame` to ensure there's no other thread that could replace the + -- `Throw e` instruction. We schedule the `thread'`, it will run `Throw e` + -- directly before any future `reschedule`. + let thread' = thread { threadControl = ThreadControl (Throw e) ctl + , threadThrowTo = etids } + (unblocked, + simstate') = unblockThreads False [l_labelled tid'] simstate + in do + trace <- schedule thread' simstate' + return $ SimTrace time tid tlbl (EventThrowToUnmasked tid') + $ traceMany [ (time, tid'', tlbl'', EventThrowToWakeup) + | tid'' <- unblocked + , let tlbl'' = lookupThreadLabel tid'' threads ] + trace +schedulePendingThrowTo _ _ = + error "IOSim: schedulePendingThrowTo: no pending async exceptions" + +-- | Drop the pending async exceptions thrown by the given thread. +-- +-- Used when a thread blocked in `throwTo` is interrupted: its `throwTo` is +-- cancelled. 'BlockedOnThrowTo' does not record the target, but a thread is +-- blocked in at most one `throwTo`, so it is safe to apply it to all threads. +-- +dropThrowToFrom :: IOSimThreadId -> Thread s a -> Thread s a +dropThrowToFrom tid t = + t { threadThrowTo = filter (\(_, Labelled tid' _) -> tid' /= tid) + (threadThrowTo t) } + +-- | Put a runnable thread at the back of the runqueue. +-- +yieldThread :: Thread s a -> SimState s a -> ST s (SimTrace a) +yieldThread !thread !simstate@SimState{runqueue, threads} = + + -- We don't interrupt runnable threads to provide fairness anywhere else. + -- We do it here by putting the thread to the back of the runqueue, behind + -- all other runnable threads. + -- + -- For testing, we should have a more sophisticated policy to show that + -- algorithms are not sensitive to the exact policy, so long as it is a + -- fair policy (all runnable threads eventually run). + + let runqueue' = Deque.snoc (threadId thread) runqueue + threads' = Map.insert (threadId thread) thread threads in + reschedule simstate { runqueue = runqueue', threads = threads' } + -- When there is no current running thread but the runqueue is non-empty then -- schedule the next one to run. reschedule :: SimState s a -> ST s (SimTrace a) @@ -770,10 +950,17 @@ reschedule !simstate@SimState{ threads, timers, curTime = time } = -- Check all fired threadDelays let wakeupThreadDelay = [ (tid, tmid) | TimerThreadDelay tid tmid <- fired ] + -- preemptions that are still current (a thread unmasked when + -- preempted may have been woken by an async exception) + wakeupPreempt = [ (tid, tmid) + | TimerPreempt tid tmid <- fired + , Map.lookup tid (preempted simstate) == Just tmid ] !simstate' = - snd . unblockThreads False (fst `fmap` wakeupThreadDelay) + snd . unblockThreads False (fst `fmap` wakeupPreempt) + . snd . unblockThreads False (fst `fmap` wakeupThreadDelay) . snd . unblockThreads True wakeupSTM - $ simstate + $ simstate { preempted = foldr (Map.delete . fst) + (preempted simstate) wakeupPreempt } -- For each 'timeout' action where the timeout has fired, start a -- new thread to execute throwTo to interrupt the action. @@ -803,6 +990,9 @@ reschedule !simstate@SimState{ threads, timers, curTime = time } = ++ [ ( time', tid, Just "thread delay timer" , EventThreadDelayFired tmid) | (tid, tmid) <- wakeupThreadDelay ] + ++ [ ( time', tid, Just "preemption timer" + , EventPreemptionEnded tmid) + | (tid, tmid) <- wakeupPreempt ] ++ [ ( time', tid, Just "timeout timer" , EventTimeoutFired tmid) | (tid, tmid, _) <- timeoutExpired ] @@ -823,6 +1013,15 @@ reschedule !simstate@SimState{ threads, timers, curTime = time } = -- it's handled directly above with 'wakeupThreadDelay' and 'unblockThreads' timeoutSTMAction TimerThreadDelay{} = return () timeoutSTMAction TimerTimeout{} = return () + timeoutSTMAction TimerPreempt{} = return () + +-- | Cancel the preemption of a thread, if it is preempted. +cancelPreemption :: IOSimThreadId -> SimState s a -> SimState s a +cancelPreemption tid simstate@SimState{ preempted, timers } = + case Map.lookup tid preempted of + Nothing -> simstate + Just tmid -> simstate { preempted = Map.delete tid preempted + , timers = PSQ.delete (coerce tmid) timers } unblockThreads :: Bool -> [IOSimThreadId] -> SimState s a -> ([IOSimThreadId], SimState s a) unblockThreads !onlySTM !wakeup !simstate@SimState {runqueue, threads} = @@ -898,24 +1097,25 @@ forkTimeoutInterruptThreads timeoutExpired simState = Just t' -> t' Nothing -> error ("IOSim: internal error: unknown thread " ++ show tid) nextId = threadNextTId t + + -- assassin thread + action :: IOSim s () + action = do + mtid <- myThreadId + v2 <- atomically $ tryPutTMVar lock mtid + when v2 $ + throwTo tid (toException (TimeoutException tmid)) + in ( state { threads = Map.insert tid t { threadNextTId = succ nextId } threads } - , ( Thread { threadId = childThreadId tid nextId, - threadControl = - ThreadControl - (runIOSim $ do - -- assassin thread - mtid <- myThreadId - v2 <- atomically $ tryPutTMVar lock mtid - when v2 $ - throwTo tid (toException (TimeoutException tmid))) - ForkFrame, - threadStatus = ThreadRunning, - threadMasking = Unmasked, - threadThrowTo = [], - threadClockId = threadClockId t, - threadLabel = Just "timeout-forked-thread", - threadNextTId = 1 - } + , ( Thread { threadId = childThreadId False tid nextId, + threadControl = ThreadControl (runIOSim action) ForkFrame, + threadStatus = ThreadRunning, + threadMasking = Unmasked, + threadThrowTo = [], + threadClockId = threadClockId t, + threadLabel = Just "timeout-forked-thread", + threadNextTId = 1 + } , lock ) ) @@ -1012,7 +1212,8 @@ unwindControlStack e = \thread timers -> Just (TimeoutException tmid') | tmid == tmid' -> (Right thread { threadControl = ThreadControl (k Nothing) ctl }, timers', reverse locks) -- Exception came from a different exception. The cleanup of the - -- lock kills the assassin, if any. + -- lock kills the assassin, which retracts its pending exception, if + -- any. _ -> unwind thread ctl timers' @@ -1064,7 +1265,13 @@ lookupThreadLabel tid threads = join (threadLabel <$> Map.lookup tid threads) -- convenient way is exposed by 'Control.Monad.IOSim.runSimTrace'. -- runSimTraceST :: forall s a. IOSim s a -> ST s (SimTrace a) -runSimTraceST mainAction = schedule mainThread initialState +runSimTraceST = runSimTraceSTWith envPreemption + +-- | 'runSimTraceST' with a preemption oracle. +-- +runSimTraceSTWith :: forall s a. Preemption -> IOSim s a -> ST s (SimTrace a) +runSimTraceSTWith preemption mainAction = + schedule mainThread initialState { preemption } where mainThread = Thread { diff --git a/io-sim/src/Control/Monad/IOSim/Types.hs b/io-sim/src/Control/Monad/IOSim/Types.hs index afef532b..d150d25f 100644 --- a/io-sim/src/Control/Monad/IOSim/Types.hs +++ b/io-sim/src/Control/Monad/IOSim/Types.hs @@ -1100,6 +1100,11 @@ data SimEventType -- ^ thread delayed | EventThreadDelayFired TimeoutId -- ^ thread woken up after a delay + | EventPreempted TimeoutId Int DiffTime SI.Time + -- ^ the thread was preempted at its n-th yield point for the given time, + -- until the given time + | EventPreemptionEnded TimeoutId + -- ^ a preempted thread is runnable again | EventTimeoutCreated TimeoutId IOSimThreadId SI.Time -- ^ new timeout created (via `timeout`) @@ -1215,6 +1220,10 @@ ppSimEventType = \case show tid, " ", show t ] EventThreadDelayFired tid -> "ThreadDelayFired " ++ show tid + EventPreempted tmid n d t -> + concat [ "Preempted ", show tmid, " yield ", show n, " for ", show d, + " until ", show t ] + EventPreemptionEnded tmid -> "PreemptionEnded " ++ show tmid EventTimeoutCreated timer tid t -> concat [ "TimeoutCreated ", show timer, " ", diff --git a/io-sim/src/Control/Monad/IOSimPOR/Internal.hs b/io-sim/src/Control/Monad/IOSimPOR/Internal.hs index 244b3152..3fbfd659 100644 --- a/io-sim/src/Control/Monad/IOSimPOR/Internal.hs +++ b/io-sim/src/Control/Monad/IOSimPOR/Internal.hs @@ -53,7 +53,7 @@ import Data.List qualified as List import Data.List.Trace qualified as Trace import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map -import Data.Maybe (catMaybes, mapMaybe) +import Data.Maybe (catMaybes, isJust, mapMaybe) import Data.Ord import Data.Set (Set) import Data.Set qualified as Set @@ -103,6 +103,10 @@ data Thread s a = Thread { threadStep :: !Int, threadVClock :: VectorClock, threadEffect :: Effect, -- in the current step + -- | The `TVar`s read by the STM transaction the thread is blocked on. Only + -- valid while the thread is `BlockedOnSTM`: it is not cleared when the + -- thread wakes up. + threadWaitsOn :: !(Set (Labelled TVarId)), threadRacy :: !Bool } deriving Show @@ -122,11 +126,10 @@ threadStepId Thread{ threadId, threadStep } = (threadId, threadStep) isRacyThreadId :: IOSimThreadId -> Bool isRacyThreadId (RacyThreadId _) = True -isRacyThreadId _ = True +isRacyThreadId (ThreadId _) = False isNotRacyThreadId :: IOSimThreadId -> Bool -isNotRacyThreadId (ThreadId _) = True -isNotRacyThreadId _ = False +isNotRacyThreadId = not . isRacyThreadId bottomVClock :: VectorClock bottomVClock = VectorClock Map.empty @@ -357,6 +360,10 @@ schedule thread@Thread{ maybe (unsafeUnregisterTimeout tmid) killThread <$> closeTimeoutLock (TimeoutLock tmid lock) + -- If the assassin has already thrown, but we were not + -- interruptible, its exception is pending. `cleanup` kills the + -- assassin, which cancels its `throwTo` and retracts the pending + -- exception (see `dropThrowToFrom`). let thread' = thread { threadControl = ThreadControl (unIOSim cleanup (\() -> k (Just x))) @@ -373,30 +380,84 @@ schedule thread@Thread{ -- Found a CatchFrame (Right thread0@Thread { threadControl = ThreadControl handlerAction handlerCtl , threadMasking = maskst' + , threadThrowTo }, timers'', locks) -> do -- We found a suitable exception handler, continue with that, - -- but first cleanup any unwind `TimeoutFrame` locks. + -- but first cleanup all unwound `TimeoutFrame`s. -- We record a step, in case there is no exception handler on replay. tids <- traverse closeTimeoutLock locks let -- at least one assassin thread won the race + assassin = isJust `any` tids + cleanups :: IOSim s () cleanups = traverse_ killThread (catMaybes tids) - thread1 = thread0 { threadControl = - ThreadControl (case cleanups of - IOSim k' -> k' (\() -> handlerAction)) - handlerCtl - } + -- NOTE: we could always run the cleanups within + -- `uninterruptibleMask_` (as GHC's `cleanupTimeout` does), but + -- every `MaskFrame` pop is a step, so it would change the step + -- numbering of every caught exception. We only wrap it when it + -- matters. + -- + -- When the wrapped cleanups end, the thread unmasks back to + -- `maskst'`, which raises a pending async exception if the thread + -- is `Unmasked`. + needMask = + case maskst' of + -- the thread is not blocked, thus it is interruptible iff it + -- is `Unmasked` + Unmasked + -- at least one assassin won the race: kill all of them + -- (including the ones that are blocked on `throwTo`, or not + -- thrown yet) before any assassin's async exception is + -- delivered. Unlike in `IOSim`, `killThread` yields, so + -- without the mask an assassin which holds its lock, but + -- is not killed yet, could throw in the middle of the + -- cleanups. + | assassin + -> True + + -- there are pending async exceptions: don't raise any of + -- them until cleanup ends + | not (null threadThrowTo) + -> True + + -- otherwise none of the cleanups will be interrupted: either + -- the thread is masked, and the cleanups do not block (the + -- assassin threads are never masked, so `killThread` from + -- any of the cleanups is non-blocking), or no assassin won + -- the race, so the cleanups only unregister the timeouts, + -- and neither block nor yield. + _ -> False + thread1 = + if needMask + -- unlike in `IOSim` case we apply masking directly. Using + -- `uninterruptibleMask_` would add a scheduling point before + -- the `uninterruptibleMask_` is entered when a pending async + -- can be delivered. + then + thread0 { threadMasking = MaskedUninterruptible + , threadControl = ThreadControl + (runIOSim cleanups) + (MaskFrame (\() -> handlerAction) maskst' handlerCtl) + } + else + thread0 { threadControl = ThreadControl + (unIOSim cleanups (\() -> handlerAction)) + handlerCtl + } (thread', eff) = stepThread thread1 control' = advanceControl (threadStepId thread0) control races' = updateRaces thread0 simstate - trace <- schedule thread' simstate{ races = races', - control = control', - timers = timers'' } + trace <- schedule thread' + simstate{ races = races', + control = control', + timers = timers'' } return (SimPORTrace time tid tstep tlbl (EventThrow e) $ SimPORTrace time tid tstep tlbl (EventMask maskst') $ + traceMany [ (time, tid, tstep, tlbl, EventMask MaskedUninterruptible) + | needMask ] $ SimPORTrace time tid tstep tlbl (EventEffect vClock eff) $ - SimPORTrace time tid tstep tlbl (EventRaces races') + SimPORTrace time tid tstep tlbl (EventRaces races') $ trace) (Left isMain, timers'', locks) @@ -417,7 +478,9 @@ schedule thread@Thread{ -- blocked on it is woken up by `deschedule Terminated`. traverse_ closeTimeoutLock locks let terminated = Terminated - !trace <- deschedule terminated thread simstate { timers = timers'' } + !trace <- deschedule terminated + thread + simstate { timers = timers'' } return $ SimPORTrace time tid tstep tlbl (EventThrow e) $ SimPORTrace time tid tstep tlbl (EventThreadUnhandled e) $ SimPORTrace time tid tstep tlbl (EventDeschedule terminated) @@ -506,7 +569,9 @@ schedule thread@Thread{ (TimeoutFrame nextTmid lock k ctl) } trace <- deschedule Yield thread' simstate { timers = timers' - , nextTmid = succ nextTmid } + , nextTmid = succ nextTmid + , nextVid = succ nextVid + } return (SimPORTrace time tid tstep tlbl (EventTimeoutCreated nextTmid tid expiry) trace) UnregisterTimeout tmid k -> do @@ -596,7 +661,7 @@ schedule thread@Thread{ , threadEffect = effect' } (unblocked, - simstate') = unblockThreads False vClock wakeup simstate + simstate') = unblockThreads True vClock wakeup simstate modifySTRef (tvarVClock tvar) (leastUpperBoundVClock vClock) !trace <- deschedule Yield thread' simstate' { timers = timers' } return $ SimPORTrace time tid tstep tlbl (EventTimerCancelled tmid) @@ -617,9 +682,8 @@ schedule thread@Thread{ Fork a k -> do let nextTId = threadNextTId thread - tid' | threadRacy thread = setRacyThread $ childThreadId tid nextTId - | otherwise = childThreadId tid nextTId - thread' = thread { threadControl = ThreadControl (k tid') ctl, + tid' = childThreadId (threadRacy thread) tid nextTId + thread' = thread { threadControl = ThreadControl (k tid') ctl, threadNextTId = nextTId + 1, threadEffect = effect <> forkEffect tid' @@ -637,6 +701,7 @@ schedule thread@Thread{ , threadVClock = insertVClock tid' 0 $ vClock , threadEffect = mempty + , threadWaitsOn = Set.empty , threadRacy = threadRacy thread } threads' = Map.insert tid' thread'' threads @@ -708,9 +773,11 @@ schedule thread@Thread{ vids <- traverse (\(SomeTVar tvar) -> labelledTVarId tvar) read vClockRead <- leastUpperBoundTVarVClocks read read' <- mapM someTVarToLabelled read - let effect' = effect <> readEffects read' + let readEffect = readEffects read' + effect' = effect <> readEffect thread' = thread { threadVClock = vClock `leastUpperBoundVClock` vClockRead, - threadEffect = effect' } + threadEffect = effect', + threadWaitsOn = effectReads readEffect } !trace <- deschedule (Blocked BlockedOnSTM) thread' simstate return $ SimPORTrace time tid tstep tlbl (EventTxBlocked vids (Just effect')) $ SimPORTrace time tid tstep tlbl (EventDeschedule (Blocked BlockedOnSTM)) @@ -780,7 +847,8 @@ schedule thread@Thread{ ThrowTo e tid' k -> do let thread' = thread { threadControl = ThreadControl k ctl, threadEffect = effect <> throwToEffect tid' - <> wakeUpEffect, + <> wakeUpEffect + <> interruptEffect, threadVClock = vClock `leastUpperBoundVClock` vClockTgt } (vClockTgt, @@ -790,18 +858,41 @@ schedule thread@Thread{ not (threadInterruptible t || isThreadDone t)) where Just t = Map.lookup tid' threads + -- If the exception interrupts a blocked transaction, this step + -- races with writes to the `TVar`s the transaction waits on: if + -- one of them wakes the thread up first, the exception finds it + -- runnable, and if it is masked, not interruptible. + interruptEffect + | not willBlock + , Just Thread { threadStatus = ThreadBlocked BlockedOnSTM + , threadWaitsOn = tvars } + <- Map.lookup tid' threads + = mempty { effectReads = tvars } + | otherwise + = mempty + if willBlock - then do - -- The target thread has async exceptions masked so we add the - -- exception and the source thread id to the pending async exceptions. - let adjustTarget t = - t { threadThrowTo = (e, Labelled tid tlbl, vClock) : threadThrowTo t } - threads' = Map.adjust adjustTarget tid' threads - trace <- deschedule (Blocked BlockedOnThrowTo) thread' simstate { threads = threads' } - return $ SimPORTrace time tid tstep tlbl (EventThrowTo e tid') - $ SimPORTrace time tid tstep tlbl EventThrowToBlocked - $ SimPORTrace time tid tstep tlbl (EventDeschedule (Blocked BlockedOnThrowTo)) - $ trace + then case threadThrowTo thread of + -- `throwTo` blocks, which is an interruptible point: if we have + -- pending async exceptions, and are not `MaskedUninterruptible`, + -- one of them is raised instead, and `e` is neither thrown nor + -- traced. We keep the throw effect: whether `e` is thrown depends + -- on the masking state of the target. + _ : _ | maskst /= MaskedUninterruptible -> do + trace <- schedulePendingThrowToAndDeschedule thread' simstate + return $ SimPORTrace time tid tstep tlbl (EventDeschedule Interruptable) + $ trace + _ -> do + -- The target thread has async exceptions masked so we add the + -- exception and the source thread id to the pending async exceptions. + let adjustTarget t = + t { threadThrowTo = (e, Labelled tid tlbl, vClock) : threadThrowTo t } + threads' = Map.adjust adjustTarget tid' threads + trace <- deschedule (Blocked BlockedOnThrowTo) thread' simstate { threads = threads' } + return $ SimPORTrace time tid tstep tlbl (EventThrowTo e tid') + $ SimPORTrace time tid tstep tlbl EventThrowToBlocked + $ SimPORTrace time tid tstep tlbl (EventDeschedule (Blocked BlockedOnThrowTo)) + $ trace else do -- The target thread has async exceptions unmasked, or is masked but -- is blocked (and all blocking operations are interruptible) then we @@ -811,20 +902,78 @@ schedule thread@Thread{ -- be resolved if the thread terminates or if it leaves the exception -- handler (when restoring the masking state would trigger the any -- new pending async exception). - let adjustTarget t@Thread{ threadControl = ThreadControl _ ctl', + -- + -- If the target thread is blocked in `throwTo`, interrupting it + -- cancels its `throwTo`: we drop its exception from the pending + -- async exceptions of its target, which might be this thread. + -- + -- The target thread is `MaskedInterruptible`, to make subsequent + -- `throwTo` to that thread blocking, otherwise they will again + -- again land in this branch and overwrite a pending throw. When the + -- `e` is thrown, the masking state is restored. + let adjustTarget :: Thread s a -> Thread s a + adjustTarget t@Thread{ threadControl = ThreadControl _ ctl', + threadMasking = maskst', threadVClock = vClock' } = - t { threadControl = ThreadControl (Throw e) ctl' - , threadStatus = if isThreadDone t - then threadStatus t - else ThreadRunning - , threadVClock = vClock' `leastUpperBoundVClock` vClock } - (_unblocked, simstate'@SimState { threads = threads' }) = unblockThreads False vClock [tid'] simstate + if isThreadDone t + then + t { threadControl = ThreadControl (Throw e) ctl' + , threadVClock = vClock' `leastUpperBoundVClock` vClock + } + else + t { threadControl = ThreadControl (Throw e) + (MaskFrame Return maskst' ctl') + , threadMasking = MaskedInterruptible + , threadStatus = ThreadRunning + , threadVClock = vClock' `leastUpperBoundVClock` vClock + } + + cancelThrowTo :: Bool + cancelThrowTo = case Map.lookup tid' threads of + Just Thread { threadStatus = ThreadBlocked BlockedOnThrowTo } + -> True + _ -> False + + -- the other threads whose pending async exceptions change: + -- this step races with their steps + cancelledTargets :: [IOSimThreadId] + cancelledTargets = + [ threadId t + | cancelThrowTo + , t <- Map.elems threads + , not (isThreadDone t) + , any (\(_, Labelled tid'' _, _) -> tid'' == tid') + (threadThrowTo t) + ] + + thread'' + | cancelThrowTo = (dropThrowToFrom tid' thread') + { threadEffect = threadEffect thread' + <> foldMap throwToEffect cancelledTargets + } + | otherwise = thread' + + -- the targets whose pending async exceptions change happen + -- after this step + cancelThrowToAt :: Thread s a -> Thread s a + cancelThrowToAt t + | threadId t `elem` cancelledTargets + = (dropThrowToFrom tid' t) + { threadVClock = threadVClock t `leastUpperBoundVClock` vClock } + | otherwise + = t + + simstate0 + | cancelThrowTo = simstate { threads = Map.map cancelThrowToAt threads } + | otherwise = simstate + simstate'@SimState { threads = threads' } + = snd (unblockThreads False vClock [tid'] simstate0) threads'' = Map.adjust adjustTarget tid' threads' simstate'' = simstate' { threads = threads'' } -- We yield at this point because the target thread may be higher -- priority, so this should be a step for race detection. - trace <- deschedule Yield thread' simstate'' + trace <- deschedule Yield thread'' simstate'' return $ SimPORTrace time tid tstep tlbl (EventThrowTo e tid') $ trace @@ -892,40 +1041,13 @@ deschedule Yield thread@Thread { threadId = tid, races = races', control = control' } -deschedule Interruptable thread@Thread { - threadId = tid, - threadStep = tstep, - threadControl = ThreadControl _ ctl, - threadMasking = Unmasked, - threadThrowTo = (e, tid', vClock') : etids, - threadLabel = tlbl, - threadVClock = vClock, - threadEffect = effect - } - simstate@SimState{ curTime = time, threads } = do - - let effect' = effect <> wakeupEffects unblocked - -- We're unmasking, but there are pending blocked async exceptions. - -- So immediately raise the exception and unblock the blocked thread - -- if possible. - thread' = thread { threadControl = ThreadControl (Throw e) ctl - , threadMasking = MaskedInterruptible - , threadThrowTo = etids - , threadVClock = vClock `leastUpperBoundVClock` vClock' - , threadEffect = effect' - } - (unblocked, - simstate') = unblockThreads False vClock [l_labelled tid'] simstate - -- the thread is stepped when we Yield - !trace <- deschedule Yield thread' simstate' - return $ SimPORTrace time tid tstep tlbl (EventThrowToUnmasked tid') - $ SimPORTrace time tid tstep tlbl (EventEffect vClock effect') - -- TODO: step - $ traceMany [ (time, tid'', (-1), tlbl'', EventThrowToWakeup) - | tid'' <- unblocked - , let tlbl'' = lookupThreadLabel tid'' threads ] - $ SimPORTrace time tid tstep tlbl (EventDeschedule Yield) - trace +deschedule Interruptable thread@Thread { threadMasking = Unmasked + , threadThrowTo = _ : _ } + simstate = + -- We're unmasking, but there are pending blocked async exceptions. + -- So immediately raise the exception and unblock the blocked thread + -- if possible. + schedulePendingThrowToAndDeschedule thread simstate deschedule Interruptable thread@Thread{threadId = tid, threadStep = tstep, @@ -958,7 +1080,7 @@ deschedule (Blocked _blockedReason) thread@Thread { threadId = tid -- exceptions. So immediately raise the exception and unblock the blocked -- thread if possible. SimPORTrace time tid tstep tlbl (EventDeschedule Interruptable) <$> - deschedule Interruptable thread { threadMasking = Unmasked } simstate + schedulePendingThrowToAndDeschedule thread simstate deschedule (Blocked blockedReason) thread@Thread{ threadId = tid, threadStep = tstep, @@ -1016,6 +1138,70 @@ deschedule Sleep thread@Thread { threadId = tid , threadEffect = effect' } threads' = Map.insert tid thread threads in reschedule simstate { runqueue = runqueue', threads = threads' } +-- | Raise the first pending async exception of a thread, and unblock the +-- thread which threw it. +-- +schedulePendingThrowToAndDeschedule + :: Thread s a + -> SimState s a + -> ST s (SimTrace a) +schedulePendingThrowToAndDeschedule thread@Thread { + threadId = tid, + threadStep = tstep, + threadControl = ThreadControl _ ctl, + threadMasking = maskst, + threadThrowTo = (e, tid', vClock') : etids, + threadLabel = tlbl, + threadVClock = vClock, + threadEffect = effect + } + simstate@SimState{ curTime = time, threads } = do + + let effect' = effect <> wakeupEffects unblocked + -- adding `MaskFrame` to restore the masking state back to `maskst` and + -- set the masking state to `MaskedInterruptible`. + -- + -- This makes raising the exception atomic. It stops `throwTo` from + -- another thread replacing the pending `Throw e` before that + -- `Throw` has run. Since the thread is not blocked, `willBlock` is + -- `True` and the thread that issues `throwTo` is blocked before it can + -- modify control frame. + -- + -- This differs from IOSim case, since next we run `deschedule Yield` + -- which might pick another thread to run before we handle `Throw e`. + thread' = thread { threadControl = ThreadControl (Throw e) + (MaskFrame Return maskst ctl) + , threadMasking = MaskedInterruptible + , threadThrowTo = etids + , threadVClock = vClock `leastUpperBoundVClock` vClock' + , threadEffect = effect' + } + (unblocked, + simstate') = unblockThreads False vClock [l_labelled tid'] simstate + -- the thread is stepped when we Yield + !trace <- deschedule Yield thread' simstate' + return $ SimPORTrace time tid tstep tlbl (EventThrowToUnmasked tid') + $ SimPORTrace time tid tstep tlbl (EventEffect vClock effect') + -- TODO: step + $ traceMany [ (time, tid'', (-1), tlbl'', EventThrowToWakeup) + | tid'' <- unblocked + , let tlbl'' = lookupThreadLabel tid'' threads ] + $ SimPORTrace time tid tstep tlbl (EventDeschedule Yield) + trace +schedulePendingThrowToAndDeschedule _ _ = + error "IOSimPOR: schedulePendingThrowToAndDeschedule: no pending async exceptions" + +-- | Drop the pending async exceptions thrown by the given thread. +-- +-- Used when a thread blocked in `throwTo` is interrupted: its `throwTo` is +-- cancelled. 'BlockedOnThrowTo' does not record the target, but a thread is +-- blocked in at most one `throwTo`, so it is safe to apply it to all threads. +-- +dropThrowToFrom :: IOSimThreadId -> Thread s a -> Thread s a +dropThrowToFrom tid t = + t { threadThrowTo = filter (\(_, Labelled tid' _, _) -> tid' /= tid) + (threadThrowTo t) } + -- Choose the next thread to run. reschedule :: SimState s a -> ST s (SimTrace a) @@ -1231,18 +1417,19 @@ forkTimeoutInterruptThreads timeoutExpired simState = Just t' -> t' Nothing -> error ("IOSimPOR: internal error: unknown thread " ++ show tid) nextId = threadNextTId t - tid' = childThreadId tid nextId + tid' = childThreadId (threadRacy t) tid nextId + + -- assassin thread + action :: IOSim s () + action = do + mtid <- myThreadId + v2 <- atomically $ tryPutTMVar lock mtid + when v2 $ + throwTo tid (toException (TimeoutException tmid)) + in ( state { threads = Map.insert tid t { threadNextTId = succ nextId } threads } , ( Thread { threadId = tid', - threadControl = - ThreadControl - (runIOSim $ do - -- assassin thread - mtid <- myThreadId - v2 <- atomically $ tryPutTMVar lock mtid - when v2 $ - throwTo tid (toException (TimeoutException tmid))) - ForkFrame, + threadControl = ThreadControl (runIOSim action) ForkFrame, threadStatus = ThreadRunning, threadMasking = Unmasked, threadThrowTo = [], @@ -1253,6 +1440,7 @@ forkTimeoutInterruptThreads timeoutExpired simState = threadVClock = insertVClock tid' 0 $ threadVClock t, threadEffect = mempty, + threadWaitsOn = Set.empty, threadRacy = threadRacy t } , lock @@ -1351,7 +1539,8 @@ unwindControlStack e = \thread timers -> Just (TimeoutException tmid') | tmid == tmid' -> (Right thread { threadControl = ThreadControl (k Nothing) ctl }, timers', reverse locks) -- Exception came from a different exception. The cleanup of the - -- lock kills the assassin, if any. + -- lock kills the assassin, which retracts its pending exception, if + -- any. _ -> unwind thread ctl timers' @@ -1428,6 +1617,7 @@ controlSimTraceST limit control mainAction = threadStep = 0, threadVClock = insertVClock (ThreadId []) 0 bottomVClock, threadEffect = mempty, + threadWaitsOn = Set.empty, threadRacy = False } diff --git a/io-sim/src/Control/Monad/IOSimPOR/QuickCheckUtils.hs b/io-sim/src/Control/Monad/IOSimPOR/QuickCheckUtils.hs index efc3a95d..df8a7bb8 100644 --- a/io-sim/src/Control/Monad/IOSimPOR/QuickCheckUtils.hs +++ b/io-sim/src/Control/Monad/IOSimPOR/QuickCheckUtils.hs @@ -2,43 +2,52 @@ module Control.Monad.IOSimPOR.QuickCheckUtils where +import Control.Exception (evaluate) import Control.Parallel -import Test.QuickCheck.Gen +import System.IO.Unsafe (unsafePerformIO) import Test.QuickCheck.Property --- Take the conjunction of several properties, in parallel This is a --- modification of code from Test.QuickCheck.Property, to run non-IO --- properties in parallel. It also takes care NOT to label its result --- as an IO property (using IORose), unless one of its arguments is --- itself an IO property. This is needed to permit parallel testing. -conjoinPar :: TestableNoCatch prop => [prop] -> Property -conjoinPar = conjoinSpeculate speculate - where - -- speculation tries to evaluate each Rose tree in parallel, to WHNF - -- This will not perform any IO, but should evaluate non-IO properties - -- completely. - speculate [] = [] - speculate (rose:roses) = roses' `par` rose' `pseq` (rose':roses') - where rose' = case rose of - MkRose result _ -> (case ok result of { Nothing -> (); Just !_ -> (); }) - `pseq` rose - IORose _ -> rose - roses' = speculate roses - --- We also need a version of conjoin that is sequential, but does not --- label its result as an IO property unless one of its arguments --- is. Consequently it does not catch exceptions in its arguments. -conjoinNoCatch :: TestableNoCatch prop => [prop] -> Property -conjoinNoCatch = conjoinSpeculate id - -conjoinSpeculate :: TestableNoCatch prop => ([Rose Result] -> [Rose Result]) -> [prop] -> Property -conjoinSpeculate spec ps = - againNoCatch $ +-- Take the conjunction of several properties, in parallel. This is a +-- modification of code from Test.QuickCheck.Property. +-- +-- All conjuncts but the first one are sparked; the first one is reduced by +-- the thread which reduces the conjunction. An 'IORose' is reduced with +-- 'unsafePerformIO': the properties built by 'exploreSimTrace' are always +-- 'IORose's, since QuickCheck's combinators ('counterexample', 'tabulate', +-- ...) wrap them in exception handlers, but the IO they do is evaluation. +-- +-- The sparks are created by the 'IORose' action of the conjunction, which +-- runs once per reduction of the conjunction. Had they been created while +-- evaluating a lazy list, two threads could evaluate the same list cell +-- (lazy black-holing), and the thread which loses that race would leave +-- behind sparks which reduce the remaining conjuncts a second time. +-- 'unsafePerformIO' (rather than 'unsafeDupablePerformIO') ensures that the +-- thread which consumes the conjunction and a spark do not both reduce the +-- same conjunct. +conjoinPar :: Testable prop => [prop] -> Property +conjoinPar ps = MkProperty $ - do roses <- mapM (fmap unProp . unProperty . propertyNoCatch) ps - return (MkProp $ conj id (spec roses)) - where - + do roses <- mapM (fmap unProp . unProperty . property) ps + return $ MkProp $ IORose $ do + let roses' = map speculate roses + mapM_ (\rose -> evaluate (rose `par` ())) (drop 1 roses') + return (conjRoses roses') + where + speculate rose = case rose of + MkRose result _ -> forceResult result `pseq` rose + IORose _ -> + case unsafePerformIO (reduceRose rose) of + rose'@(MkRose result _) -> forceResult result `pseq` rose' + rose' -> rose' + + forceResult result = case ok result of { Nothing -> (); Just !_ -> () } + +-- | Conjunction of rose trees. It runs the 'IO' of each 'IORose' at most +-- once. +conjRoses :: [Rose Result] -> Rose Result +conjRoses = conj id + where + conj :: (Result -> Result) -> [Rose Result] -> Rose Result conj k [] = MkRose (k succeeded) [] @@ -48,15 +57,15 @@ conjoinSpeculate spec ps = _ | not (expect result) -> return failed { reason = "expectFailure may not occur inside a conjunction" } Just True -> conj (addLabels result . addCallbacksAndCoverage result . k) ps - Just False -> p + Just False -> return result Nothing -> do let rest = conj (addCallbacksAndCoverage result . k) ps result2 <- rest -- Nasty work to make sure we use the right callbacks case ok result2 of Just True -> MkRose (result2 { ok = Nothing }) [] - Just False -> rest - Nothing -> rest + Just False -> return result2 + Nothing -> return result2 addCallbacksAndCoverage result r = r { callbacks = callbacks result ++ callbacks r, @@ -65,45 +74,3 @@ conjoinSpeculate spec ps = r { labels = labels result ++ labels r, classes = classes result ++ classes r, tables = tables result ++ tables r } - - --- .&&| is a sequential, but parallelism-friendly version of .&&., that --- tests its arguments in sequence, but does not label its result as --- an IO property unless one of its arguments is. - -infixr 1 .&&| -(.&&|) :: TestableNoCatch prop => prop -> prop -> Property -p .&&| q = conjoinNoCatch [p, q] - - --- property catches exceptions in its argument, turning everything --- Testable into an IORose property, which cannot be paralellized. We --- need an alternative that permits parallelism by allowing exceptions --- to propagate. This is a modified clone of code from --- Test.QuickCheck.Property. - -class TestableNoCatch prop where - propertyNoCatch :: prop -> Property - -instance TestableNoCatch Discard where - propertyNoCatch _ = propertyNoCatch rejected - -instance TestableNoCatch Bool where - propertyNoCatch = propertyNoCatch . liftBool - -instance TestableNoCatch Result where - propertyNoCatch = MkProperty . return . MkProp . return - -instance TestableNoCatch Prop where - propertyNoCatch p = MkProperty . return $ p - -instance TestableNoCatch prop => TestableNoCatch (Gen prop) where - propertyNoCatch mp = MkProperty $ do p <- mp; unProperty (againNoCatch $ propertyNoCatch p) - -instance TestableNoCatch Property where - propertyNoCatch p = p - -againNoCatch :: Property -> Property -againNoCatch (MkProperty gen) = MkProperty $ do - MkProp rose <- gen - return . MkProp $ fmap (\res -> res{ abort = False }) rose diff --git a/io-sim/src/Control/Monad/IOSimPOR/Types.hs b/io-sim/src/Control/Monad/IOSimPOR/Types.hs index 16385aa1..106b7f01 100644 --- a/io-sim/src/Control/Monad/IOSimPOR/Types.hs +++ b/io-sim/src/Control/Monad/IOSimPOR/Types.hs @@ -110,6 +110,12 @@ racingEffects e e' = -- concurrent writes to the same TVars || effectWrites e `intersects` effectWrites e' + -- one effect wakes up a thread which the other one throws to: the + -- order decides if the exception finds the thread blocked, hence + -- interruptible even if it is masked + || effectWakeup e `intersectsSL` effectThrows e' + || effectWakeup e' `intersectsSL` effectThrows e + where intersects :: Ord a => Set a -> Set a -> Bool intersects a b = not $ a `Set.disjoint` b @@ -117,6 +123,9 @@ racingEffects e e' = intersectsL :: Eq a => [a] -> [a] -> Bool intersectsL a b = not $ null $ a `List.intersect` b + intersectsSL :: Ord a => Set a -> [a] -> Bool + intersectsSL a b = any (`Set.member` a) b + --- --- Schedules diff --git a/io-sim/test/Main.hs b/io-sim/test/Main.hs index 8fe2080d..5cabcc36 100644 --- a/io-sim/test/Main.hs +++ b/io-sim/test/Main.hs @@ -5,6 +5,7 @@ import Test.Tasty import Test.Control.Concurrent.Class.MonadMVar qualified (tests) import Test.Control.Concurrent.Class.MonadMVar.Strict qualified (tests) import Test.Control.Monad.IOSim qualified (tests) +import Test.Control.Monad.IOSim.Preemption qualified (tests) import Test.Control.Monad.IOSimPOR qualified (tests) main :: IO () @@ -16,5 +17,6 @@ tests = [ Test.Control.Concurrent.Class.MonadMVar.tests , Test.Control.Concurrent.Class.MonadMVar.Strict.tests , Test.Control.Monad.IOSim.tests + , Test.Control.Monad.IOSim.Preemption.tests , Test.Control.Monad.IOSimPOR.tests ] diff --git a/io-sim/test/Test/Control/Monad/IOSim.hs b/io-sim/test/Test/Control/Monad/IOSim.hs index 816bb6b9..620f2da6 100644 --- a/io-sim/test/Test/Control/Monad/IOSim.hs +++ b/io-sim/test/Test/Control/Monad/IOSim.hs @@ -67,8 +67,18 @@ tests = , testProperty "async exceptions 1" unit_timeouts_and_async_exceptions_1 , testProperty "async exceptions 2" unit_timeouts_and_async_exceptions_2 , testProperty "async exceptions 3" unit_timeouts_and_async_exceptions_3 + , testProperty "assassin: pending throw" + $ forall_masking_states unit_timeout_assassin_pending_throw , testProperty "assassin: holds the lock" $ forall_masking_states unit_timeout_assassin_holds_lock + , testProperty "assassin: frame unwound" + $ forall_masking_states unit_timeout_assassin_frame_unwound + , testProperty "assassin: frame unwound, pending throw" + $ forall_masking_states unit_timeout_assassin_frame_unwound_pending_throw + , testProperty "assassin: stacked frames unwound" + $ forall_masking_states unit_timeout_assassin_stacked_frames_unwound + , testProperty "assassin: stacked timeouts fire" + $ forall_masking_states unit_timeout_assassin_stacked_timeouts_fire , testProperty "forwarded timeout exception" unit_timeout_forwarded_exception , testProperty "threadDelay and STM" unit_threadDelay_and_stm @@ -122,6 +132,20 @@ tests = , testProperty "catch (IOSim)" $ forall_masking_states unit_catch_throwIO_masking_state_ST + , testProperty "catch: restores masking state (IO)" + $ forall_masking_states $ \ms -> + forall_masking_states $ \ms' -> unit_catch_restores_masking_state_IO ms ms' + , testProperty "catch: restores masking state (IOSim)" + $ forall_masking_states $ \ms -> + forall_masking_states $ \ms' -> unit_catch_restores_masking_state_ST ms ms' + + , testProperty "timeout: restores masking state (IO)" + $ forall_masking_states $ \ms -> + forall_masking_states $ \ms' -> unit_timeout_restores_masking_state_IO ms ms' + , testProperty "timeout: restores masking state (IOSim)" + $ forall_masking_states $ \ms -> + forall_masking_states $ \ms' -> unit_timeout_restores_masking_state_ST ms ms' + , testProperty "catch: throwTo (IO)" $ forall_masking_states unit_catch_throwTo_masking_state_IO , testProperty "catch: throwTo (IOSim)" @@ -160,6 +184,38 @@ tests = , testProperty "15" unit_async_15 , testProperty "16" unit_async_16 ] + , testGroup "pending async exceptions: throwTo" + [ testProperty "not overwritten by throwTo (IO)" + unit_throwTo_does_not_overwrite_pending_exception_IO + , testProperty "not overwritten by throwTo (IOSim)" + unit_throwTo_does_not_overwrite_pending_exception_ST + ] + , testGroup "pending async exceptions" + [ testProperty "raised when timeout returns, at blocking op (IO)" + unit_timeout_raises_pending_exception_at_blocking_op_IO + , testProperty "raised when timeout returns, at blocking op (IOSim)" + unit_timeout_raises_pending_exception_at_blocking_op_ST + , testProperty "stacked timeouts: inner assassin not leaked (IO)" + unit_timeout_stacked_pending_exception_IO + , testProperty "stacked timeouts: inner assassin not leaked (IOSim)" + unit_timeout_stacked_pending_exception_ST + , testProperty "forwarded timeout exception, rethrown (IO)" + unit_timeout_forwarded_exception_rethrown_IO + , testProperty "forwarded timeout exception, rethrown (IOSim)" + unit_timeout_forwarded_exception_rethrown_ST + , testProperty "raised when timeout returns, on unmask (IO)" + unit_timeout_raises_pending_exception_on_unmask_IO + , testProperty "raised when timeout returns, on unmask (IOSim)" + unit_timeout_raises_pending_exception_on_unmask_ST + ] + , testGroup "throwTo cancellation" + [ testProperty "interrupted by a pending exception" + unit_throwTo_interrupted_by_pending_exception_ST + , testProperty "thrower killed" + unit_throwTo_thrower_killed_ST + , testProperty "thrower not woken" + unit_throwTo_cancelled_thrower_not_woken_ST + ] , testGroup "STM reference semantics" [ testProperty "Reference vs IO" prop_stm_referenceIO , testProperty "Reference vs Sim" prop_stm_referenceSim @@ -717,7 +773,7 @@ unit_async_10 = once $ say "child 1" yield say "child 1 running" - say "never 1" + say "child 1 survived" tid2 <- forkIO $ do threadDelay 1 say "child 2" @@ -734,7 +790,9 @@ unit_async_10 = once $ say "parent done" ) === - ["child 1", "child 2", "child 1 running", "parent done"] + -- child 2 is interrupted while blocked in `throwTo`, which cancels it, so + -- child 1 never receives its exception (as in GHC) + ["child 1", "child 2", "child 1 running", "child 1 survived", "parent done"] unit_async_11 = once $ @@ -745,7 +803,7 @@ unit_async_11 = once $ say "child 1" yield say "child 1 running" - say "never 1" + say "child 1 survived" tid2 <- forkIO $ -- Same as unit_async_10 but we run masked here -- this is subtle: when the main thread throws the @@ -766,7 +824,9 @@ unit_async_11 = once $ say "parent done" ) === - ["child 1", "child 2", "child 1 running", "parent done"] + -- child 2 is interrupted while blocked in `throwTo`, which cancels it, so + -- child 1 never receives its exception (as in GHC) + ["child 1", "child 2", "child 1 running", "child 1 survived", "parent done"] unit_async_12 = once $ @@ -1057,6 +1117,9 @@ prop_timeouts times = (numFailures <= maxFailures) +data TimeoutResult = OuterTimeout | InnerTimeout | Result + deriving (Eq, Ord, Show) + prop_stacked_timeouts :: TimeoutDuration -> TimeoutDuration -> ActionDuration @@ -1066,23 +1129,27 @@ prop_stacked_timeouts timeout0 timeout1 actionDuration = counterexample (ppTrace_ trace) $ either (\e -> counterexample (show e) False) (=== predicted) (traceResult False trace) where - experiment :: IOSim s (Maybe (Maybe ())) - experiment = timeout timeout0 (timeout timeout1 (threadDelay actionDuration)) + experiment :: IOSim s TimeoutResult + experiment = fn <$> timeout timeout0 (timeout timeout1 (threadDelay actionDuration)) + where + fn Nothing = OuterTimeout + fn (Just Nothing) = InnerTimeout + fn (Just (Just _)) = Result predicted | timeout0 == 0 - = Nothing + = OuterTimeout | timeout1 == 0 - = Just Nothing + = InnerTimeout | actionDuration <= min timeout0 timeout1 - = Just (Just ()) + = Result - | timeout0 < timeout1 - = Nothing + | timeout0 <= timeout1 + = OuterTimeout - | otherwise -- i.e. timeout0 >= timeout1 - = Just Nothing + | otherwise -- i.e. timeout0 > timeout1 + = InnerTimeout -- | Check that `discardAfter` works as expected. @@ -1190,6 +1257,35 @@ unit_timeouts_and_async_exceptions_3 = once $ return $ property True +-- | The assassin of a `timeout` throws while the timed thread is masked and +-- runnable, so its exception is pending when the action finishes. It must +-- not be raised after `timeout` returns (#269). +-- +-- The flag is set when the timeout fires. The writer runs first (woken by its +-- timer), then the assassin (forked at the same time, queued after it), then +-- the timed thread (woken by the write). +-- +unit_timeout_assassin_pending_throw :: MaskingState -> Property +unit_timeout_assassin_pending_throw ms = once $ + let trace = runSimTrace experiment in + counterexample (ppTrace_ trace) + . either (\e -> counterexample (show e) False) id + . traceResult False + $ trace + where + experiment :: IOSim s Property + experiment = do + flag <- newTVarIO False + _ <- forkIO $ threadDelay 1 >> atomically (writeTVar flag True) + r <- setMaskingState_ ms $ + timeout 1 (atomically (readTVar flag >>= check)) + return $ case ms of + -- the exception is delivered within the `timeout` + Unmasked -> r === Nothing + -- the exception is pending until the action finishes + _ -> r === Just () + + -- | The assassin of a `timeout` takes the lock, but the action finishes -- before it throws. The exception must not be raised after `timeout` -- returns (#269). @@ -1215,9 +1311,113 @@ unit_timeout_assassin_holds_lock ms = once $ return (r === Just ()) +-- | The action throws at the deadline, and the exception unwinds through the +-- `TimeoutFrame`. The assassin is forked, but has not run yet: it must not +-- throw after the frame is left (#269). +-- +-- The timed thread is woken by its `threadDelay` timer before the assassin is +-- forked, so it throws first. +-- +unit_timeout_assassin_frame_unwound :: MaskingState -> Property +unit_timeout_assassin_frame_unwound ms = once $ + let trace = runSimTrace experiment in + counterexample (ppTrace_ trace) + . either (\e -> counterexample (show e) False) id + . traceResult False + $ trace + where + experiment :: IOSim s Property + experiment = do + r <- try $ setMaskingState_ ms $ + timeout 1 (threadDelay 1 >> throwIO DivideByZero) + -- an interruptible point, a stale exception would be raised here + threadDelay 1 + return (r === (Left DivideByZero :: Either ArithException (Maybe ()))) + + +-- | The assassin of a `timeout` throws while the timed thread is masked, then +-- the action throws, and the exception unwinds through the `TimeoutFrame`. +-- The pending exception must not be raised after the frame is left (#269). +-- +unit_timeout_assassin_frame_unwound_pending_throw :: MaskingState -> Property +unit_timeout_assassin_frame_unwound_pending_throw ms = once $ + let trace = runSimTrace experiment in + counterexample (ppTrace_ trace) + . either (\e -> counterexample (show e) False) id + . traceResult False + $ trace + where + experiment :: IOSim s Property + experiment = do + r <- try $ setMaskingState_ ms $ + timeout 1 (uninterruptibleMask_ (threadDelay 2 >> throwIO DivideByZero)) + -- an interruptible point, a stale exception would be raised here + threadDelay 1 + return (r === (Left DivideByZero :: Either ArithException (Maybe ()))) + + +-- | Like 'unit_timeout_assassin_frame_unwound', but the exception unwinds +-- through two `TimeoutFrame`s, whose assassins are both forked (#269). +-- +unit_timeout_assassin_stacked_frames_unwound :: MaskingState -> Property +unit_timeout_assassin_stacked_frames_unwound ms = once $ + let trace = runSimTrace experiment in + counterexample (ppTrace_ trace) + . either (\e -> counterexample (show e) False) id + . traceResult False + $ trace + where + experiment :: IOSim s Property + experiment = do + r <- try $ setMaskingState_ ms $ + timeout 1 (timeout 1 (threadDelay 1 >> throwIO DivideByZero)) + -- interruptible points, a stale exception would be raised here + threadDelay 1 + threadDelay 1 + return $ case r :: Either ArithException (Maybe (Maybe ())) of + Left DivideByZero -> property True + -- one of the timeouts won + Right Nothing -> property True + Right (Just Nothing) -> property True + _ -> counterexample (show r) False + + +-- | Two stacked timeouts fire at the same time. The exception of one of them +-- unwinds through the `TimeoutFrame` of the other one, whose assassin has +-- already thrown. Its exception must not be raised after the frame is left +-- (#269). +-- +-- Under `MaskedUninterruptible` neither exception can be delivered, so both +-- frames are left normally. +-- +unit_timeout_assassin_stacked_timeouts_fire :: MaskingState -> Property +unit_timeout_assassin_stacked_timeouts_fire ms = once $ + let trace = runSimTrace experiment in + counterexample (ppTrace_ trace) + . either (\e -> counterexample (show e) False) id + . traceResult False + $ trace + where + experiment :: IOSim s Property + experiment = do + r <- setMaskingState_ ms $ + timeout 1 (timeout 1 (threadDelay 2)) + -- interruptible points, a stale exception would be raised here + threadDelay 1 + threadDelay 1 + return $ case (ms, r) of + (MaskedUninterruptible, Just (Just ())) -> property True + (MaskedUninterruptible, _) -> counterexample (show r) False + (_, Nothing) -> property True + (_, Just Nothing) -> property True + (_, Just (Just _)) -> counterexample (show r) False + + -- | The timed thread catches the `TimeoutException` of its `timeout`, and -- another thread throws it back while the timed thread is masked within the --- frame. The forwarded exception must be raised after the frame is left. +-- frame. Leaving the frame must only retract the assassin's exception, not +-- the forwarded one: otherwise the forwarding thread stays blocked in +-- `throwTo` forever. -- unit_timeout_forwarded_exception :: Property unit_timeout_forwarded_exception = once $ @@ -1382,6 +1582,22 @@ unit_catch_throwIO_masking_state_ST :: MaskingState -> Property unit_catch_throwIO_masking_state_ST ms = once $ runSimOrThrow (prop_catch_throwIO_masking_state ms) +unit_catch_restores_masking_state_IO :: MaskingState -> MaskingState -> Property +unit_catch_restores_masking_state_IO ms ms' = once $ + ioProperty $ prop_catch_restores_masking_state ms ms' + +unit_catch_restores_masking_state_ST :: MaskingState -> MaskingState -> Property +unit_catch_restores_masking_state_ST ms ms' = once $ + runSimOrThrow (prop_catch_restores_masking_state ms ms') + +unit_timeout_restores_masking_state_IO :: MaskingState -> MaskingState -> Property +unit_timeout_restores_masking_state_IO ms ms' = once $ + ioProperty $ prop_timeout_restores_masking_state ms ms' + +unit_timeout_restores_masking_state_ST :: MaskingState -> MaskingState -> Property +unit_timeout_restores_masking_state_ST ms ms' = once $ + runSimOrThrow (prop_timeout_restores_masking_state ms ms') + unit_catch_throwTo_masking_state_IO :: MaskingState -> Property unit_catch_throwTo_masking_state_IO = once . ioProperty . prop_catch_throwTo_masking_state @@ -1599,3 +1815,81 @@ tryReadEmptyTBQueue sndRead = atomically $ do counterexamples :: Testable t => [String] -> t -> Property counterexamples [] p = property p counterexamples (c:cs) p = counterexample c (counterexamples cs p) + +-- | Similar to `ioProperty`. +-- +ioSimProperty + :: Testable property + => Bool + -- ^ if True the property will fail if there are any threads which + -- didn't terminate when the main thread terminated. + -> (forall s. IOSim s property) + -> Property +ioSimProperty strict iosim = + let trace = runSimTrace iosim in + counterexample (ppTrace_ trace) + . either (\e -> counterexample (show e) False) + property + . traceResult strict + $ trace + + +unit_timeout_raises_pending_exception_at_blocking_op_IO :: Property +unit_timeout_raises_pending_exception_at_blocking_op_IO = + once $ ioProperty prop_timeout_raises_pending_exception_at_blocking_op + +unit_timeout_raises_pending_exception_at_blocking_op_ST :: Property +unit_timeout_raises_pending_exception_at_blocking_op_ST = + once $ ioSimProperty False + $ prop_timeout_raises_pending_exception_at_blocking_op + +unit_timeout_stacked_pending_exception_IO :: Property +unit_timeout_stacked_pending_exception_IO = + once $ ioProperty prop_timeout_stacked_pending_exception + +-- | The simulation also fails if any thread, e.g. the inner assassin, is +-- still running or blocked when the main thread returns. +-- +unit_timeout_stacked_pending_exception_ST :: Property +unit_timeout_stacked_pending_exception_ST = + once $ ioSimProperty True prop_timeout_stacked_pending_exception + +unit_throwTo_does_not_overwrite_pending_exception_IO :: Property +unit_throwTo_does_not_overwrite_pending_exception_IO = + once $ ioProperty prop_throwTo_does_not_overwrite_pending_exception + +unit_throwTo_does_not_overwrite_pending_exception_ST :: Property +unit_throwTo_does_not_overwrite_pending_exception_ST = + once $ ioSimProperty False prop_throwTo_does_not_overwrite_pending_exception + +unit_timeout_forwarded_exception_rethrown_IO :: Property +unit_timeout_forwarded_exception_rethrown_IO = + once $ ioProperty prop_timeout_forwarded_exception_rethrown + +unit_timeout_forwarded_exception_rethrown_ST :: Property +unit_timeout_forwarded_exception_rethrown_ST = + once $ ioSimProperty False prop_timeout_forwarded_exception_rethrown + +unit_timeout_raises_pending_exception_on_unmask_IO :: Property +unit_timeout_raises_pending_exception_on_unmask_IO = + once $ ioProperty prop_timeout_raises_pending_exception_on_unmask + +unit_timeout_raises_pending_exception_on_unmask_ST :: Property +unit_timeout_raises_pending_exception_on_unmask_ST = + once $ ioSimProperty False prop_timeout_raises_pending_exception_on_unmask + +unit_throwTo_interrupted_by_pending_exception_ST :: Property +unit_throwTo_interrupted_by_pending_exception_ST = + once $ ioSimProperty False prop_throwTo_interrupted_by_pending_exception + +unit_throwTo_thrower_killed_ST :: Property +unit_throwTo_thrower_killed_ST = + once $ ioSimProperty False prop_throwTo_thrower_killed + +unit_throwTo_cancelled_thrower_not_woken_ST :: Property +unit_throwTo_cancelled_thrower_not_woken_ST = once $ + let trace = runSimTrace prop_throwTo_cancelled_thrower_not_woken in + counterexample (ppTrace_ trace) + . either (\e -> counterexample (show e) False) id + . traceResult False + $ trace diff --git a/io-sim/test/Test/Control/Monad/IOSim/Preemption.hs b/io-sim/test/Test/Control/Monad/IOSim/Preemption.hs new file mode 100644 index 00000000..e515110c --- /dev/null +++ b/io-sim/test/Test/Control/Monad/IOSim/Preemption.hs @@ -0,0 +1,173 @@ +{-# LANGUAGE NumericUnderscores #-} + +-- | Properties of the preemption oracle ('runSimTraceWith'). +module Test.Control.Monad.IOSim.Preemption (tests) where + +import Control.Concurrent.Class.MonadSTM +import Control.Monad (forM, forM_, replicateM_) +import Control.Monad.Class.MonadFork +import Control.Monad.Class.MonadThrow +import Control.Monad.Class.MonadTime.SI +import Control.Monad.Class.MonadTimer.SI +import Control.Monad.IOSim + +import Test.QuickCheck +import Test.Tasty +import Test.Tasty.QuickCheck + +tests :: TestTree +tests = + testGroup "Preemption" + [ testProperty "window opens iff the oracle preempts long enough" prop_window + , testProperty "preemptionsOf replays the run" prop_replay + , testProperty "transactions stay atomic" prop_atomic + , testProperty "a masked thread is not interrupted while preempted" prop_masked + , testProperty "an interrupted preemption leaves no timer behind" prop_interrupted + ] + +-- | A random oracle: seed, probability (permille) and maximal delay (µs). +data Spec = Spec Int Int Int + deriving Show + +instance Arbitrary Spec where + arbitrary = Spec <$> arbitrary <*> choose (0, 1000) <*> choose (1, 10_000) + shrink (Spec s p m) = + [ Spec s p' m | p' <- shrink p, p' >= 0 ] + ++ [ Spec s p m' | m' <- shrink m, m' >= 1 ] + +oracle :: Spec -> Preemption +oracle (Spec s p m) = preemptRandom s (fromIntegral p / 1000) (micros m) + +micros :: Int -> DiffTime +micros n = fromIntegral n / 1_000_000 + +-- | The writer commits 1 then 2; the reader reads at @d@ (half a microsecond +-- off the oracle's grid, so no tie). It sees 1 iff the writer was preempted +-- at its first yield point (after the first commit) for longer than @d@. +prop_window :: Spec -> NonNegative Int -> Property +prop_window spec (NonNegative dUs) = + let d = micros dUs + 0.000_000_5 + (seen, writer) = runSimOrThrowWith (oracle spec) $ do + v <- newTVarIO (0 :: Int) + r <- newEmptyTMVarIO + w <- forkIO $ atomically (writeTVar v 1) >> atomically (writeTVar v 2) + _ <- forkIO $ threadDelay d >> readTVarIO v >>= atomically . putTMVar r + x <- atomically (takeTMVar r) + return (x, w) + expected = case preemptAt (oracle spec) writer 0 of + Just p | p > d -> 1 + _ -> 2 + in counterexample (show (writer, preemptAt (oracle spec) writer 0, d)) + $ cover 10 (expected == 1) "window open" + $ seen === expected + +runSimOrThrowWith :: Preemption -> (forall s. IOSim s a) -> a +runSimOrThrowWith p a = either (error . show) id (runSimWith p a) + +-- | Threads doing increments with delays between them. +incrementers :: [[Int]] -> IOSim s Int +incrementers delays = do + v <- newTVarIO 0 + dones <- forM delays $ \ds -> do + done <- newEmptyTMVarIO + _ <- forkIO $ do + forM_ ds $ \d -> do + threadDelay (micros d) + atomically (readTVar v >>= writeTVar v . succ) + yield + atomically (putTMVar done ()) + return done + mapM_ (atomically . takeTMVar) dones + readTVarIO v + +genDelays :: Gen [[Int]] +genDelays = listOf1 (listOf1 (choose (0, 5_000))) + +-- | Replaying the preemptions a random run made gives the same trace. +prop_replay :: Spec -> Property +prop_replay spec = + forAllShrink genDelays shrink $ \delays -> + let t = runSimTraceWith (oracle spec) (incrementers delays) + ps = preemptionsOf t + t' = runSimTraceWith (preemptFromMap ps) (incrementers delays) + in cover 50 (not (null ps)) "preempted" + $ ppTrace_ t === ppTrace_ t' + +-- | Every increment lands, whatever the preemptions. +prop_atomic :: Spec -> Property +prop_atomic spec = + forAllShrink (choose (1, 6)) shrink $ \n -> + forAllShrink (choose (1, 20)) shrink $ \k -> + let r = runSimWith (oracle spec) $ do + v <- newTVarIO (0 :: Int) + dones <- forM [1 .. n] $ \_ -> do + done <- newEmptyTMVarIO + _ <- forkIO $ replicateM_ k (atomically (modifyTVar' v succ)) + >> atomically (putTMVar done ()) + return done + mapM_ (atomically . takeTMVar) dones + readTVarIO v + in counterexample (show r) (either (const False) (== n * k) r) + +-- | A masked thread writes @a@ then @b@ in two transactions; it is killed at +-- @dK@. A preemption between the transactions is no interruptible point, so +-- @a@ implies @b@. +prop_masked :: Spec -> NonNegative Int -> NonNegative Int -> Property +prop_masked spec (NonNegative dT) (NonNegative dK) = + let (a, b, t) = runSimOrThrowWith (oracle spec) $ do + va <- newTVarIO False + vb <- newTVarIO False + done <- newEmptyTMVarIO + tid <- forkIO $ (threadDelay (micros dT) >> mask_ (do + atomically (writeTVar va True) + atomically (writeTVar vb True))) + `finally` atomically (putTMVar done ()) + threadDelay (micros dK + 0.000_000_5) + killThread tid + atomically (takeTMVar done) + (,,) <$> readTVarIO va <*> readTVarIO vb <*> pure tid + -- the thread's first yield point is after writing @a@ + kill = micros dK + 0.000_000_5 + inside = case preemptAt (oracle spec) t 0 of + Just p -> micros dT < kill && kill < micros dT + p + Nothing -> False + in cover 5 inside "killed while preempted between the writes" + $ counterexample (show (a, b)) + $ not a || b + +data Interrupt = Interrupt + deriving Show +instance Exception Interrupt + +-- | A sleep (µs), on the scale of the oracle's delays. +newtype Sleep = Sleep Int + deriving Show + +instance Arbitrary Sleep where + arbitrary = Sleep <$> choose (1, 20_000) + shrink (Sleep n) = [ Sleep m | m <- shrink n, m >= 1 ] + +-- | An unmasked thread is interrupted at @dK@ (perhaps while preempted after +-- its first commit), catches the exception and sleeps @dD@: it sleeps +-- exactly @dD@, even when its preemption would have ended during the sleep. +prop_interrupted :: Spec -> NonNegative Int -> Sleep -> Property +prop_interrupted spec (NonNegative dK) (Sleep dD) = + let (slept, tid) = runSimOrThrowWith (oracle spec) $ do + r <- newEmptyTMVarIO + v <- newTVarIO (0 :: Int) + t <- forkIO $ (atomically (writeTVar v 1) >> threadDelay 1000) + `catch` \Interrupt -> do + t0 <- getMonotonicTime + threadDelay (micros dD) + t1 <- getMonotonicTime + atomically (putTMVar r (t1 `diffTime` t0)) + threadDelay (micros dK + 0.000_000_5) + throwTo t Interrupt + (,) <$> atomically (takeTMVar r) <*> pure t + kill = micros dK + 0.000_000_5 + pre = preemptAt (oracle spec) tid 0 + inside = maybe False (kill <) pre + ends = maybe False (< kill + micros dD) pre + in cover 10 inside "interrupted while preempted" + $ cover 5 (inside && ends) "preemption would end during the sleep" + $ slept === micros dD diff --git a/io-sim/test/Test/Control/Monad/IOSimPOR.hs b/io-sim/test/Test/Control/Monad/IOSimPOR.hs index 061b8f37..add0ec58 100644 --- a/io-sim/test/Test/Control/Monad/IOSimPOR.hs +++ b/io-sim/test/Test/Control/Monad/IOSimPOR.hs @@ -17,6 +17,8 @@ import Data.Functor (($>)) import Data.List qualified as List import Data.Map (Map) import Data.Map qualified as Map +import Data.Set (Set) +import Data.Set qualified as Set import System.Exit import System.IO.Error (ioeGetErrorString, isUserError) @@ -67,6 +69,12 @@ tests = , testProperty "racy" unit_issue113_racy , testProperty "nonDep" unit_issue113_nonDep ] + , testGroup "throwTo races with a wake-up" + [ testProperty "thrower runs first" + (unit_throwTo_races_with_wakeup False) + , testProperty "writer runs first" + (unit_throwTo_races_with_wakeup True) + ] -- , testProperty "propPermutations" propPermutations ] , testGroup "IO simulator properties" @@ -78,6 +86,14 @@ tests = , testProperty "timeouts" prop_timeouts , testProperty "stacked timeouts" prop_stacked_timeouts , testProperty "{register,thread}Delay" unit_registerDelay_threadDelay + -- When unmasked, the exception of the assassin is raised as soon as + -- it is thrown, so the paths these tests are for are never reached. + , testProperty "assassin: pending throw" + $ forall_masked_states unit_timeout_assassin_pending_throw + , testProperty "assassin: holds the lock" + $ forall_masked_states unit_timeout_assassin_holds_lock + , testProperty "assassin: frame unwound" + $ forall_masked_states unit_timeout_assassin_frame_unwound , testProperty "forwarded timeout exception" unit_timeout_forwarded_exception ] @@ -139,6 +155,28 @@ tests = , testProperty "8" unit_async_8 , testProperty "9" unit_async_9 ] + , testGroup "pending async exceptions: throwTo" + [ testProperty "not overwritten by throwTo" + unit_throwTo_does_not_overwrite_pending_exception_ST + ] + , testGroup "pending async exceptions" + [ testProperty "raised when timeout returns, at blocking op" + unit_timeout_raises_pending_exception_at_blocking_op_ST + , testProperty "stacked timeouts: inner assassin not leaked" + unit_timeout_stacked_pending_exception_ST + , testProperty "forwarded timeout exception, rethrown" + unit_timeout_forwarded_exception_rethrown_ST + , testProperty "raised when timeout returns, on unmask" + unit_timeout_raises_pending_exception_on_unmask_ST + ] + , testGroup "throwTo cancellation" + [ testProperty "interrupted by a pending exception" + unit_throwTo_interrupted_by_pending_exception_ST + , testProperty "thrower killed" + unit_throwTo_thrower_killed_ST + , testProperty "thrower not woken" + unit_throwTo_cancelled_thrower_not_woken_ST + ] , testGroup "STM reference semantics" [ testProperty "Reference vs Sim" prop_stm_referenceSim ] @@ -420,6 +458,67 @@ unit_issue113_nonDep = Task [ThrowTo 1]] +-- | A `throwTo` to a masked thread, which is blocked in STM, races with a write +-- which wakes the thread up: +-- +-- * if the exception is thrown first, the thread is blocked, hence +-- interruptible, so the exception is raised at once and the transaction +-- doesn't commit; +-- * if the write is first, the thread is runnable, so the exception is pending +-- until the thread unmasks, after the transaction committed. +-- +-- IOSimPOR must explore both orders, whichever of them runs first. +-- +unit_throwTo_races_with_wakeup :: Bool -- ^ whether the writer runs first + -> Property +unit_throwTo_races_with_wakeup writerFirst = + once $ exploreSimResults experiment $ \results -> + counterexample ("explored results: " ++ show (Set.toList results)) $ + results === Set.fromList [False, True] + where + -- returns whether the blocked transaction committed + experiment :: IOSim s Bool + experiment = do + exploreRaces + flag <- newTVarIO False + committed <- newTVarIO False + t <- async $ mask_ $ atomically $ do + readTVar flag >>= check + writeTVar committed True + let writer = threadDelay 1 >> atomically (writeTVar flag True) + thrower = threadDelay 1 >> throwTo (asyncThreadId t) DivideByZero + -- at time 1, the thread forked last runs first, since it has the larger + -- thread id + ws <- if writerFirst + then do a <- async thrower + w <- async writer + return [a, w] + else do w <- async writer + a <- async thrower + return [w, a] + _ <- waitCatch t + traverse_ wait ws + readTVarIO committed + + +-- | Explore the schedules of a simulation, and check the set of results of all +-- the explored schedules. +-- +exploreSimResults :: Ord a + => (forall s. IOSim s a) + -> (Set a -> Property) + -> Property +exploreSimResults sim k = ioProperty $ do + r <- newIORef Set.empty + return $ + exploreSimTrace id sim + (\_ trace -> case traceResult False trace of + Right a -> ioProperty (modifyIORef' r (Set.insert a) $> True) + Left e -> counterexample (show e) False) + -- `.&&.` checks all the explored schedules before the results + .&&. ioProperty (k <$> readIORef r) + + -- Testing propPermutations n should collect every permutation of [1..n] once only. -- Test manually, and supply a small value of n. propPermutations :: Int -> Property @@ -1026,6 +1125,8 @@ prop_timeouts times = exploreSimTrace id experiment $ \_ trace -> ("too many failures: " ++ show numFailures ++ " ≰ " ++ show maxFailures) (numFailures <= maxFailures) +data TimeoutResult = OuterTimeout | InnerTimeout | Result + deriving (Eq, Ord, Show) prop_stacked_timeouts :: DiffTime -> DiffTime @@ -1034,29 +1135,68 @@ prop_stacked_timeouts :: DiffTime prop_stacked_timeouts timeout0 timeout1 actionDuration = exploreSimTrace id experiment $ \_ trace -> case traceResult False trace of - Right result -> result === predicted + Right result -> counterexample ("predicted: " ++ show predicted) + $ result === expected + .&&. counterexample "the expected result is not predicted" + (expected `elem` predicted) Left e -> counterexample (show e) False where - experiment :: IOSim s (Maybe (Maybe ())) + experiment :: IOSim s TimeoutResult experiment = exploreRaces - >> timeout timeout0 (timeout timeout1 (threadDelay actionDuration)) + >> fn <$> timeout timeout0 (timeout timeout1 (threadDelay actionDuration)) + where + fn Nothing = OuterTimeout + fn (Just Nothing) = InnerTimeout + fn (Just (Just _)) = Result + predicted :: [TimeoutResult] predicted | timeout0 == 0 - = Nothing + = [OuterTimeout] | timeout1 == 0 - = Just Nothing + = [InnerTimeout] - -- This differs from `IOSim` case; `IOSimPOR` is using - -- different scheduler. | actionDuration < min timeout0 timeout1 - = Just (Just ()) + = [Result] + + -- The action finishes when a timeout fires, either of them can + -- win. This differs from `IOSim` case; `IOSimPOR` is using + -- different scheduler. + | actionDuration == min timeout0 timeout1 + = Result : [ OuterTimeout | timeout0 == actionDuration ] + ++ [ InnerTimeout | timeout1 == actionDuration ] | timeout0 < timeout1 - = Nothing + = [OuterTimeout] + + -- both timeouts fire at the same time, either of them can win + | timeout0 == timeout1 + = [OuterTimeout, InnerTimeout] + + | otherwise -- i.e. timeout0 > timeout1 + = [InnerTimeout] + + -- The result of the only schedule which `IOSimPOR` explores. The + -- timeouts run in the main thread, whose thread id is not racy, so its + -- steps do not start races and a tie is decided by the default schedule: + -- the action wins a tie with a timeout, and the outer timeout wins a tie + -- with the inner one. Checking that all the `predicted` results are + -- explored needs `IOSimPOR` to explore these races. + expected :: TimeoutResult + expected | timeout0 == 0 + = OuterTimeout - | otherwise -- i.e. timeout0 >= timeout1 - = Just Nothing + | timeout1 == 0 + = InnerTimeout + + | actionDuration <= min timeout0 timeout1 + = Result + + | timeout0 <= timeout1 + = OuterTimeout + + | otherwise + = InnerTimeout unit_registerDelay_threadDelay :: Property unit_registerDelay_threadDelay = @@ -1172,9 +1312,37 @@ ioSimPORProperty strict iosim = $ trace +-- | The assassin of a `timeout` throws while the timed thread is masked and +-- runnable, so its exception is pending when the action finishes. It must +-- not be raised after `timeout` returns (#269). +-- +-- `timeout` runs in a forked thread, so that the steps of the timed thread +-- are racy: the steps of the main thread never start a race. +-- +unit_timeout_assassin_pending_throw :: MaskingState -> Property +unit_timeout_assassin_pending_throw ms = + ioSimPORProperty False experiment + where + experiment :: IOSim s Property + experiment = do + flag <- newTVarIO False + w <- async $ threadDelay 1 >> atomically (writeTVar flag True) + r <- waitCatch =<< async (setMaskingState_ ms $ + timeout 1 (atomically (readTVar flag >>= check))) + -- The simulation ends when the main thread returns: if it did not wait + -- for the writer, the writer would not run in the schedules in which + -- the assassin throws first, and their race would not be explored. + wait w + return $ case r of + Left e -> counterexample (show e) False + Right _ -> property True + + -- | The timed thread catches the `TimeoutException` of its `timeout`, and -- another thread throws it back while the timed thread is masked within the --- frame. The forwarded exception must be raised after the frame is left. +-- frame. Leaving the frame must only retract the assassin's exception, not +-- the forwarded one: otherwise the forwarding thread stays blocked in +-- `throwTo` forever. -- unit_timeout_forwarded_exception :: Property unit_timeout_forwarded_exception = @@ -1201,6 +1369,55 @@ unit_timeout_forwarded_exception = return $ counterexample (show r) $ isLeft (r :: Either SomeException ()) + +-- | The assassin of a `timeout` takes the lock, but the action finishes +-- before it throws. The exception must not be raised after `timeout` +-- returns (#269). +-- +-- `timeout` runs in a forked thread, so that the steps of the timed thread +-- are racy: the steps of the main thread never start a race. +-- +unit_timeout_assassin_holds_lock :: MaskingState -> Property +unit_timeout_assassin_holds_lock ms = + ioSimPORProperty False experiment + where + experiment :: IOSim s Property + experiment = do + r <- waitCatch =<< async (setMaskingState_ ms $ + timeout 1 (threadDelay 1 >> atomically (return ()))) + return $ case r of + Left e -> counterexample (show e) False + Right _ -> property True + + +-- | The action throws at the deadline, and the exception unwinds through the +-- `TimeoutFrame` and is caught outside of it. The assassin must not throw +-- after the frame is left, and its exception must not be pending (#269). +-- +-- `timeout` runs in a forked thread, so that the steps of the timed thread +-- are racy: the steps of the main thread never start a race. +-- +unit_timeout_assassin_frame_unwound :: MaskingState -> Property +unit_timeout_assassin_frame_unwound ms = + ioSimPORProperty False experiment + where + experiment :: IOSim s Property + experiment = do + r <- waitCatch =<< async (do + r <- try $ setMaskingState_ ms $ + timeout 1 ( threadDelay 1 + >> atomically (return ()) + >> throwIO DivideByZero) + -- an interruptible point, a stale exception would be raised here + threadDelay 1 + return (r :: Either ArithException (Maybe ()))) + return $ case r of + Left e -> counterexample (show e) False + -- the timeout won + Right (Right Nothing) -> property True + Right (Left DivideByZero) -> property True + Right r' -> counterexample (show r') False + -- -- MonadMask properties -- @@ -1260,3 +1477,50 @@ unit_catch_throwTo_masking_state_async_mayblock_ST ms = case traceResult False trace of Right a -> a Left e -> counterexample (show e) False + +unit_timeout_raises_pending_exception_at_blocking_op_ST :: Property +unit_timeout_raises_pending_exception_at_blocking_op_ST = + once $ ioSimPORProperty False + $ prop_timeout_raises_pending_exception_at_blocking_op + +-- | The simulation also fails if any thread, e.g. the inner assassin, is +-- still running or blocked when the main thread returns. +-- +unit_timeout_stacked_pending_exception_ST :: Property +unit_timeout_stacked_pending_exception_ST = + once $ ioSimPORProperty True + $ prop_timeout_stacked_pending_exception + +unit_throwTo_does_not_overwrite_pending_exception_ST :: Property +unit_throwTo_does_not_overwrite_pending_exception_ST = + once $ ioSimPORProperty False + $ prop_throwTo_does_not_overwrite_pending_exception + +unit_timeout_forwarded_exception_rethrown_ST :: Property +unit_timeout_forwarded_exception_rethrown_ST = + once $ ioSimPORProperty False + $ prop_timeout_forwarded_exception_rethrown + +unit_timeout_raises_pending_exception_on_unmask_ST :: Property +unit_timeout_raises_pending_exception_on_unmask_ST = + once $ ioSimPORProperty False + $ prop_timeout_raises_pending_exception_on_unmask + +unit_throwTo_interrupted_by_pending_exception_ST :: Property +unit_throwTo_interrupted_by_pending_exception_ST = + once $ ioSimPORProperty False + $ prop_throwTo_interrupted_by_pending_exception + +unit_throwTo_thrower_killed_ST :: Property +unit_throwTo_thrower_killed_ST = + once $ ioSimPORProperty False $ prop_throwTo_thrower_killed + +unit_throwTo_cancelled_thrower_not_woken_ST :: Property +unit_throwTo_cancelled_thrower_not_woken_ST = once $ + exploreSimTrace id + (exploreRaces >> prop_throwTo_cancelled_thrower_not_woken) + $ \_ trace -> + counterexample (ppTrace_ trace) + . either (\e -> counterexample (show e) False) id + . traceResult False + $ trace diff --git a/io-sim/test/Test/Control/Monad/Utils.hs b/io-sim/test/Test/Control/Monad/Utils.hs index fe673618..c5e9bd77 100644 --- a/io-sim/test/Test/Control/Monad/Utils.hs +++ b/io-sim/test/Test/Control/Monad/Utils.hs @@ -2,16 +2,19 @@ module Test.Control.Monad.Utils where import Data.Array +import Data.Either (isLeft) import Data.Fixed (Fixed (..), Micro) import Data.Function (on) import Data.Graph import Data.List (sortBy) +import Control.Exception (AsyncException, ErrorCall (..)) import Control.Monad import Control.Concurrent.Class.MonadSTM.Strict import Control.Monad.Class.MonadFork import Control.Monad.Class.MonadThrow +import Control.Monad.Class.MonadTime.SI import Control.Monad.Class.MonadTimer.SI import Control.Monad.IOSim @@ -409,6 +412,40 @@ prop_catch_throwIO_masking_state ms = ms' <- getMaskingState return $ ms' === MaskedInterruptible `maxMS` ms +-- | The masking state is restored when an exception, thrown under a different +-- masking state, is caught. The exception is thrown under @ms'@: @restore@ +-- unmasks first, since @'setMaskingState_' 'Unmasked'@ does not unmask. +-- +prop_catch_restores_masking_state :: forall m. MonadMask m + => MaskingState + -> MaskingState + -> m Property +prop_catch_restores_masking_state ms ms' = + setMaskingState ms $ \restore -> do + _ <- try @_ @IOError $ + restore (setMaskingState_ ms' (throwIO (userError "error"))) + ms'' <- getMaskingState + return $ ms'' === ms + +-- | The masking state is restored when 'timeout' fires, whatever the masking +-- state of the timed action. The action runs under @ms'@ (see +-- 'prop_catch_restores_masking_state'), and the timeout is set to fire before +-- it finishes. +-- +prop_timeout_restores_masking_state :: forall m. ( MonadMask m + , MonadDelay m + , MonadTimer m + ) + => MaskingState + -> MaskingState + -> m Property +prop_timeout_restores_masking_state ms ms' = + setMaskingState ms $ \restore -> do + -- timeout before the action finish + _ <- timeout 0.01 (restore (setMaskingState_ ms' (threadDelay 0.05))) + ms'' <- getMaskingState + return $ ms'' === ms + -- | Like 'prop_catch_masking_state' but using 'throwTo'. -- prop_catch_throwTo_masking_state :: forall m. @@ -500,6 +537,17 @@ forall_masking_states prop = (property True) [Unmasked, MaskedInterruptible, MaskedUninterruptible] +-- | Like `forall_masking_states`, but only for the masked states. +-- +forall_masked_states :: (MaskingState -> Property) + -> Property +forall_masked_states prop = + -- make sure that the property is executed once! + withNumTests 1 $ + foldr (\ms p -> counterexample (show ms) (prop ms) .&&. p) + (property True) + [MaskedInterruptible, MaskedUninterruptible] + -- -- Utils -- @@ -514,3 +562,266 @@ selectTraceSay (SimPORTrace _ _ _ _ (EventSay msg) trace) = msg : selectTraceSay selectTraceSay (SimPORTrace _ _ _ _ _ trace) = selectTraceSay trace selectTraceSay _ = [] + +-- +-- `throwTo` and pending async exceptions +-- + +-- | A `throwTo` must not replace an async exception which was raised in its +-- target, but which the target has not run yet. +-- +-- `killThread` is synchronous: `t` dies of `ThreadKilled` (which +-- @'try' \@ErrorCall@ does not catch), and the second `throwTo` finds it +-- dead. +-- +prop_throwTo_does_not_overwrite_pending_exception + :: forall m. ( MonadDelay m + , MonadFork m + , MonadMask m + , MonadSTM m + ) + => m Property +prop_throwTo_does_not_overwrite_pending_exception = do + res <- newTVarIO Nothing + t <- forkIO $ do + r <- try @_ @ErrorCall (threadDelay 1) + atomically (writeTVar res (Just r)) + -- let `t` block in `threadDelay` + threadDelay 0.01 + killThread t + throwTo t (ErrorCall "second") + threadDelay 0.1 + r <- readTVarIO res + return $ counterexample "`t` survived" $ r === Nothing + + +-- +-- Pending async exceptions +-- + +-- | When `timeout` returns unmasked, a pending async exception is raised +-- straight away: the code after `timeout` does not run. +-- +-- @C@'s exception, and then the timeout's, are queued while the timed action +-- is uninterruptibly masked. The timed action decides where the timeout's +-- exception is raised. +-- +timeout_raises_pending_exception + :: forall m. ( MonadDelay m + , MonadFork m + , MonadMask m + , MonadTimer m + ) + => (DiffTime -> m ()) + -- ^ timed action + -> m Property +timeout_raises_pending_exception action = do + me <- myThreadId + after <- newTVarIO False + _ <- forkIO $ threadDelay t0 >> throwTo me (ErrorCall "from C") + r <- try @_ @ErrorCall $ do + _ <- timeout t1 (action t1) + -- `C`'s exception must be raised before this runs + atomically (writeTVar after True) + threadDelay t1 + ran <- readTVarIO after + return $ r === Left (ErrorCall "from C") + .&&. counterexample "the code after `timeout` ran" (not ran) + where + t0 = 0.05 + t1 = 2 * t0 + +-- | See 'timeout_raises_pending_exception': the timeout's exception is raised +-- at a blocking operation within `mask_`, and unwinds through its +-- 'MaskFrame', which restores 'Unmasked'. +-- +prop_timeout_raises_pending_exception_at_blocking_op + :: forall m. ( MonadDelay m + , MonadFork m + , MonadMask m + , MonadTimer m + ) + => m Property +prop_timeout_raises_pending_exception_at_blocking_op = + timeout_raises_pending_exception + (\t1 -> mask_ $ uninterruptibleMask_ (threadDelay (t1 + 0.1)) + >> threadDelay t1) + +-- | Two stacked timeouts. The outer one catches its own exception after it +-- unwound the inner `TimeoutFrame`, whose assassin has thrown and still holds +-- its lock, while another async exception is pending. The pending exception +-- is raised when `timeout` returns (see 'timeout_raises_pending_exception'), +-- and the inner assassin must still be killed: run with a strict shutdown +-- check, the simulation fails if it is left blocked in its `throwTo`. +-- +-- @C@'s exception, and then the inner and the outer timeout's, are queued +-- while the timed action is uninterruptibly masked. The outer timeout's +-- exception is raised first, and unwinds through the inner `TimeoutFrame`. +-- +prop_timeout_stacked_pending_exception + :: forall m. ( MonadDelay m + , MonadFork m + , MonadMask m + , MonadTimer m + ) + => m Property +prop_timeout_stacked_pending_exception = do + me <- myThreadId + _ <- forkIO $ threadDelay t0 >> throwTo me (ErrorCall "from C") + r <- try @_ @ErrorCall $ + timeout t2 (timeout t1 (uninterruptibleMask_ (threadDelay t3))) + -- let the other threads finish + threadDelay t4 + return $ r === Left (ErrorCall "from C") + + where + t0 = 0.05 + t1 = 0.1 + t2 = 0.15 + t3 = 0.3 + t4 = 0.35 + +-- | The timed action catches the timeout's exception, and another thread +-- forwards it back while the action is uninterruptibly masked. Then the +-- action rethrows it, so it unwinds to its own `TimeoutFrame` while the +-- forwarded exception is pending. Leaving the frame must not retract the +-- forwarded exception: it is raised after `timeout` returns, and the +-- forwarding thread's `throwTo` returns. Otherwise the forwarding thread +-- stays blocked in `throwTo` forever, and the simulation deadlocks. +-- +-- The forwarding thread is forked within `uninterruptibleMask_`, so in the +-- simulators its exception is pending when the action rethrows, whatever the +-- schedule. In `IO` it might be thrown later, and then it is raised at the +-- interruptible point after `timeout`. +-- +prop_timeout_forwarded_exception_rethrown + :: forall m. ( MonadDelay m + , MonadFork m + , MonadMask m + , MonadTimer m + ) + => m Property +prop_timeout_forwarded_exception_rethrown = do + me <- myThreadId + done <- newEmptyTMVarIO + r <- try @_ @SomeException $ do + _ <- timeout 0.05 $ do + -- `threadDelay` is interruptible, the timeout fires here + r' <- try @_ @SomeException (threadDelay 1) + case r' of + Left e -> uninterruptibleMask_ $ do + -- the forwarding thread blocks in `throwTo` + _ <- forkIO $ throwTo me e + >> atomically (putTMVar done ()) + threadDelay 0.05 + -- unwinds to its own `TimeoutFrame` + throwIO e + Right () -> return () + -- an interruptible point + atomically (takeTMVar done) + -- the forwarding thread's `throwTo` returned + atomically (takeTMVar done) + return $ counterexample (show r) (isLeft r) + +-- +-- Cancelling `throwTo` +-- + +-- | A thread blocked in `throwTo` is interrupted by its own pending async +-- exception. Its `throwTo` is cancelled, so the target never receives the +-- exception. +-- +-- @A@ is masked, @C@'s exception is queued while @A@ is uninterruptibly +-- masked, then @A@ blocks in `throwTo` to @B@ (uninterruptibly masked until +-- t=2), which is an interruptible point. +-- +prop_throwTo_interrupted_by_pending_exception + :: forall m. ( MonadDelay m + , MonadFork m + , MonadMask m + , MonadSTM m + ) + => m Property +prop_throwTo_interrupted_by_pending_exception = do + resA <- newTVarIO Nothing + resB <- newTVarIO Nothing + b <- uninterruptibleMask_ $ forkIOWithUnmask $ \unmask -> do + threadDelay 2 + -- a stale exception from `A` would be raised here + r <- try @_ @ErrorCall (unmask (threadDelay 1)) + atomically (writeTVar resB (Just r)) + a <- mask_ $ forkIO $ do + uninterruptibleMask_ (threadDelay 1) + r <- try @_ @ErrorCall (throwTo b (ErrorCall "from A")) + atomically (writeTVar resA (Just r)) + _ <- forkIO $ threadDelay 0.5 >> throwTo a (ErrorCall "from C") + threadDelay 6 + ra <- readTVarIO resA + rb <- readTVarIO resB + return $ ra === Just (Left (ErrorCall "from C")) + .&&. rb === Just (Right ()) + +-- | A thread blocked in `throwTo` is killed. Its `throwTo` is cancelled, so +-- the target never receives the exception. +-- +prop_throwTo_thrower_killed + :: forall m. ( MonadDelay m + , MonadFork m + , MonadMask m + , MonadSTM m + ) + => m Property +prop_throwTo_thrower_killed = do + resB <- newTVarIO Nothing + b <- uninterruptibleMask_ $ forkIOWithUnmask $ \unmask -> do + threadDelay 2 + -- a stale exception from `A` would be raised here + r <- try @_ @ErrorCall (unmask (threadDelay 1)) + atomically (writeTVar resB (Just r)) + a <- forkIO $ throwTo b (ErrorCall "from A") + threadDelay 1 + killThread a + threadDelay 5 + rb <- readTVarIO resB + return $ rb === Just (Right ()) + +-- | A thread blocked in `throwTo` is killed, and then blocks in `threadDelay`. +-- When the target unmasks, it must not wake the thread up. +-- +prop_throwTo_cancelled_thrower_not_woken + :: forall m. ( MonadDelay m + , MonadFork m + , MonadMask m + , MonadSTM m + ) + => m Property +prop_throwTo_cancelled_thrower_not_woken = do + resA <- newTVarIO Nothing + b <- uninterruptibleMask_ $ forkIOWithUnmask $ \unmask -> do + threadDelay 2 + unmask (threadDelay 1) + a <- forkIO $ + handle (\(_ :: AsyncException) -> do + t0 <- getMonotonicTime + threadDelay 100 + t1 <- getMonotonicTime + atomically (writeTVar resA (Just (t1 `diffTime` t0)))) + (throwTo b (ErrorCall "from A")) + threadDelay 1 + killThread a + d <- atomically $ readTVar resA >>= maybe retry return + return $ counterexample (show d) (d >= 100) + +-- | See 'timeout_raises_pending_exception': the timeout's exception is raised +-- when the action unmasks. +-- +prop_timeout_raises_pending_exception_on_unmask + :: forall m. ( MonadDelay m + , MonadFork m + , MonadMask m + , MonadTimer m + ) + => m Property +prop_timeout_raises_pending_exception_on_unmask = + timeout_raises_pending_exception + (uninterruptibleMask_ . threadDelay . (+0.1))