|
| 1 | +{-# LANGUAGE RecordWildCards #-} |
| 2 | +{-# LANGUAGE AllowAmbiguousTypes #-} |
| 3 | +-- | Experimental support for running parallel actions |
| 4 | +module Test.QuickCheck.ParallelActions |
| 5 | + ( RunModelPar(..) |
| 6 | + , Forking(..) |
| 7 | + , ParallelActions |
| 8 | + , runParActions |
| 9 | + ) where |
| 10 | + |
| 11 | +import Data.Set qualified as Set |
| 12 | +import Control.Monad |
| 13 | +import Control.Monad.Reader |
| 14 | +import Control.Monad.Writer |
| 15 | +import Data.Data |
| 16 | +import GHC.Generics |
| 17 | +import Test.QuickCheck hiding (Some) |
| 18 | +import Test.QuickCheck.Monadic |
| 19 | +import Test.QuickCheck.StateModel.Variables |
| 20 | +import Test.QuickCheck.StateModel |
| 21 | +import Control.Concurrent |
| 22 | +import Control.Arrow (first, second) |
| 23 | +import Data.Tree |
| 24 | + |
| 25 | +-- | The callbacks necessary to run actions in parallel |
| 26 | +class RunModel state m => RunModelPar state m where |
| 27 | + -- | Note that this version of `perform` doesn't get the current `state`. |
| 28 | + -- This is because the system is not in a definite model state during |
| 29 | + -- parallel execution. |
| 30 | + performPar :: Typeable a => Action state a -> LookUp -> m (PerformResult state m a) |
| 31 | + performPar = perform (error "Trying to evaluate state in default implementation of performPar") |
| 32 | + |
| 33 | + -- | Like `monitoring` but without the `state` |
| 34 | + monitoringPar :: Action state a -> LookUp -> Either (Error state m) a -> Property -> Property |
| 35 | + monitoringPar _ _ _ = id |
| 36 | + |
| 37 | +data ParallelActions state = |
| 38 | + ParallelActions { linearActions :: Actions state |
| 39 | + , threads :: [[Int]] |
| 40 | + } deriving (Eq, Generic) |
| 41 | + |
| 42 | +commonActions :: ParallelActions state -> [Step state] |
| 43 | +commonActions ParallelActions{linearActions = Actions steps, ..} = |
| 44 | + [ step | step@(v := _) <- steps, notElem (unsafeVarIndex v) $ concat threads ] |
| 45 | + |
| 46 | +threadActions :: ParallelActions state -> [[Step state]] |
| 47 | +threadActions ParallelActions{linearActions = Actions steps, ..} = |
| 48 | + [ [ v := s{polarity = PosPolarity} |
| 49 | + | v := s <- steps, elem (unsafeVarIndex v) thread ] |
| 50 | + | thread <- threads |
| 51 | + ] |
| 52 | + |
| 53 | +firstParAction :: ParallelActions state -> Maybe Int |
| 54 | +firstParAction ParallelActions{..} |
| 55 | + | null idxs = Nothing |
| 56 | + | otherwise = Just $ minimum idxs |
| 57 | + where idxs = concat threads |
| 58 | + |
| 59 | +instance StateModel state => Show (ParallelActions state) where |
| 60 | + show pas = |
| 61 | + unlines $ [ "-- Common Prefix:" |
| 62 | + , showWithUsed (foldMap allVariables threads) common |
| 63 | + ] ++ concat [ [ "-- Thread " ++ [n] |
| 64 | + , show thread |
| 65 | + ] |
| 66 | + | (n, thread) <- zip ['A'..'Z'] threads |
| 67 | + ] |
| 68 | + where |
| 69 | + common = Actions $ commonActions pas |
| 70 | + threads = Actions <$> threadActions pas |
| 71 | + |
| 72 | +instance StateModel state => Arbitrary (ParallelActions state) where |
| 73 | + arbitrary = genParActions |
| 74 | + |
| 75 | + shrink pas@(ParallelActions actions trs) = |
| 76 | + [ ParallelActions actions $ map (filter (/= i)) trs | Just i <- [firstParAction pas]] ++ |
| 77 | + filter checkParallelActions |
| 78 | + [ ParallelActions actions $ filter (not . null) $ map (filter (`Set.member` vars)) trs |
| 79 | + | actions <- shrink actions |
| 80 | + , let vars = unsafeIndexSet $ allVariables actions |
| 81 | + ] |
| 82 | + |
| 83 | +checkParallelActions :: StateModel state => ParallelActions state -> Bool |
| 84 | +checkParallelActions pas = all (checkWellTypedness commonCtx) (threadActions pas) |
| 85 | + where |
| 86 | + commonCtx = allVariables common |
| 87 | + common = Actions $ commonActions pas |
| 88 | + |
| 89 | +checkWellTypedness :: StateModel state => VarContext -> [Step state] -> Bool |
| 90 | +checkWellTypedness _ [] = True |
| 91 | +checkWellTypedness ctx ((v := a) : ss) = a `wellTypedIn` ctx && checkWellTypedness (extendContext ctx v) ss |
| 92 | + |
| 93 | +genParActions :: forall state. StateModel state => Gen (ParallelActions state) |
| 94 | +genParActions = do |
| 95 | + -- The ~ works around a bug in ghc (https://gitlab.haskell.org/ghc/ghc/-/issues/22004) (which is not in all ghc versions ?!) |
| 96 | + as@(~(Actions steps)) <- arbitrary |
| 97 | + let n = length steps |
| 98 | + split <- choose (max 0 (n - 20), n - 1) |
| 99 | + let (common, post) = splitAt split steps |
| 100 | + commonCtx = allVariables common |
| 101 | + tc <- choose (2, 5) |
| 102 | + threads <- go post $ replicate tc (commonCtx, []) |
| 103 | + return $ ParallelActions as $ filter (not . null) threads |
| 104 | + where go :: [Step state] -> [(VarContext, [Int])] -> Gen [[Int]] |
| 105 | + go [] trs = return $ map (reverse . snd) trs |
| 106 | + go ((v := a) : ss) trs = do |
| 107 | + let candidates = [ (ctx, tr, trs) | ((ctx, tr), trs) <- holes trs |
| 108 | + , a `wellTypedIn` ctx ] |
| 109 | + if null candidates |
| 110 | + -- This means we made a mistake earlier and split two actions whose |
| 111 | + -- result variables were used together later. At this point we just |
| 112 | + -- give up and don't extend the traces. |
| 113 | + then go [] trs |
| 114 | + else do |
| 115 | + (ctx, tr, trs) <- elements candidates |
| 116 | + go ss $ (extendContext ctx v, unsafeVarIndex v:tr) : trs |
| 117 | + |
| 118 | +data TraceStep state m where |
| 119 | + TraceStep :: (Typeable a, Show a) |
| 120 | + => Either (Error state m) a |
| 121 | + -> Var a |
| 122 | + -> ActionWithPolarity state a |
| 123 | + -> TraceStep state m |
| 124 | + |
| 125 | +type Trace state m = [TraceStep state m] |
| 126 | +type TraceTree state m = Tree (TraceStep state m) |
| 127 | + |
| 128 | +runTracing :: ( RunModelPar state m |
| 129 | + , e ~ Error state m |
| 130 | + , forall a. IsPerformResult e a |
| 131 | + ) => Env -> [Step state] -> m (Trace state m, Env) |
| 132 | +runTracing env [] = return ([], env) |
| 133 | +runTracing env ((v := ap):as) = do |
| 134 | + r <- performResultToEither <$> performPar (polarAction ap) (lookUpVar env) |
| 135 | + let step = TraceStep r v ap |
| 136 | + env' | Right val <- r = (v :== val) : env |
| 137 | + | otherwise = env |
| 138 | + (first (step :)) <$> runTracing env' as |
| 139 | + |
| 140 | +class Monad m => Forking m where |
| 141 | + forkThread :: m a -> m (m a) |
| 142 | + |
| 143 | +instance Forking IO where |
| 144 | + forkThread io = do |
| 145 | + t <- newEmptyMVar |
| 146 | + forkIO $ io >>= putMVar t |
| 147 | + return $ takeMVar t |
| 148 | + |
| 149 | +instance Forking m => Forking (ReaderT r m) where |
| 150 | + forkThread m = do |
| 151 | + reg <- ask |
| 152 | + lift $ fmap lift (forkThread $ runReaderT m reg) |
| 153 | + |
| 154 | +-- | Run parallel actions consisting of a common prefix and a number of |
| 155 | +-- parallel threads. After execution check that the preconditions were |
| 156 | +-- respected in all possible parallel executions and check that we find at |
| 157 | +-- least one parallel execution which is linearizible. |
| 158 | +runParActions :: ( StateModel state |
| 159 | + , RunModelPar state m |
| 160 | + , e ~ Error state m |
| 161 | + , forall a. IsPerformResult e a |
| 162 | + , Forking m |
| 163 | + ) => ParallelActions state -> PropertyM m () |
| 164 | +runParActions pas = do |
| 165 | + (trC, env) <- run $ runTracing mempty $ commonActions pas |
| 166 | + joins <- mapM (run . forkThread . runTracing env) (threadActions pas) |
| 167 | + trs <- mapM (fmap fst . run) joins |
| 168 | + let used = varsUsedInActions $ linearActions pas |
| 169 | + monitor $ counterexample "-- Main thread:" |
| 170 | + monitorTrace used mempty trC |
| 171 | + forM (zip ['A'..'Z'] trs) $ \ (n, tr) -> do |
| 172 | + monitor $ counterexample $ "\n-- Thread " ++ [n, ':'] |
| 173 | + monitorTrace used env tr |
| 174 | + let ilvs = prepend trC $ interleavings trs |
| 175 | + monitor $ tabulate "Trace tree size" (map (bucket . length) ilvs) |
| 176 | + assert $ null ilvs || any (checkTrace initialAnnotatedState mempty) ilvs |
| 177 | + |
| 178 | +monitorTrace :: forall state m. (StateModel state, RunModelPar state m) |
| 179 | + => VarContext -> Env -> Trace state m -> PropertyM m () |
| 180 | +monitorTrace _used _env [] = pure () |
| 181 | +monitorTrace used env (TraceStep r v act : tr) = do |
| 182 | + let showR (Right x) |
| 183 | + | v `wellTypedIn` used = show v ++ "@" ++ showsPrec 10 x "" |
| 184 | + | otherwise = show x |
| 185 | + showR (Left err) = "fail " ++ showsPrec 10 err "" |
| 186 | + monitor $ counterexample (showR r ++ " <- " ++ show (polarAction act)) |
| 187 | + monitor $ monitoringPar @state @m (polarAction act) (lookUpVar env) r |
| 188 | + monitorTrace used env' tr |
| 189 | + where |
| 190 | + env' | Right val <- r = (v :== val) : env |
| 191 | + | otherwise = env |
| 192 | + |
| 193 | +checkTrace :: forall state m. (StateModel state, RunModelPar state m) |
| 194 | + => Annotated state -> Env -> TraceTree state m -> Bool |
| 195 | +checkTrace s env (Node (TraceStep r v (ActionWithPolarity a _)) trs) = |
| 196 | + -- NOTE: we need to re-compute the polarity of `a` here because it may be that the failure can be explained, |
| 197 | + -- but only by the action failing when it was previous successful |
| 198 | + let act = actionWithPolarity s a |
| 199 | + s' = computeNextState s act v |
| 200 | + env' | Right val <- r = (v :== val) : env |
| 201 | + | otherwise = env |
| 202 | + checkPost | Right val <- r, polarity act == PosPolarity = fst . runWriter . runPost $ postcondition @state @m |
| 203 | + (underlyingState s, underlyingState s') |
| 204 | + (polarAction act) |
| 205 | + (lookUpVar env') |
| 206 | + val |
| 207 | + | Left{} <- r, polarity act == PosPolarity = False |
| 208 | + | otherwise = fst . runWriter . runPost $ postconditionOnFailure @state @m |
| 209 | + (underlyingState s, underlyingState s') |
| 210 | + (polarAction act) |
| 211 | + (lookUpVar env') |
| 212 | + r |
| 213 | + in (computePrecondition s act || discard) && checkPost && (null trs || any (checkTrace s' env') trs) |
| 214 | + |
| 215 | +prepend :: [a] -> [Tree a] -> [Tree a] |
| 216 | +prepend [] ts = ts |
| 217 | +prepend (p:ps) ts = [Node p $ prepend ps ts] |
| 218 | + |
| 219 | +interleavings :: [[a]] -> [Tree a] |
| 220 | +interleavings aas = do |
| 221 | + (a:as, os) <- holes aas |
| 222 | + pure $ Node a (interleavings (as:os)) |
| 223 | + |
| 224 | +holes :: [a] -> [(a, [a])] |
| 225 | +holes [] = [] |
| 226 | +holes (a:as) = (a, as) : map (second (a:)) (holes as) |
0 commit comments