{-# OPTIONS_GHC -fno-cse -fno-full-laziness -fno-float-in #-}
-- Avoid the test-module miscompilation matching GHC issue 27886.
module FreshRetry (freshRetry) where
import Control.Exception (evaluate)
import Control.Monad (unless)
import Control.Monad.Trans.Writer (WriterT (..))
import Data.Monoid (Product (..))
import LazyPPL (Meas (..), Prob (..), Tree (..))
import LazyPPL.SingleSite.Hooks
import System.IO.Unsafe (unsafePerformIO)
import System.Mem.StableName (makeStableName)
import System.Random (mkStdGen)
model :: Meas Double
model = Meas (WriterT (Prob pick))
where
pick (Tree _ (Tree value _ : _)) = (value, Product 1)
pick _ = error "missing child"
dirty :: Evaluator String Double
dirty fresh = do
first <- fresh
case first of Tree value _ -> evaluate value >> pure ()
firstName <- makeStableName first
pure (Suspend "wait" (do
second <- fresh
secondName <- makeStableName second
unless (firstName /= secondName) (fail "retry reused the dirty tree")
pureEvaluator model (pure second)))
check :: String -> Bool -> IO ()
check label condition = unless condition (fail label)
freshRetry :: IO ()
freshRetry = do
healthy <- either fail pure (mkKernel 0 (pureEvaluator model) uniformSites)
retrying <- either fail pure (mkKernel 0 dirty uniformSites)
let seed = mkStdGen 8802
cleanResult <- initialise healthy seed
dirtyResult <- initialise retrying seed
clean <- case cleanResult of Initialised c -> pure c; _ -> fail "clean init"
pending <- case dirtyResult of
InitialInterrupted (CallbackInterrupted "wait") p -> pure p
_ -> fail "initial suspension"
resumed <- resumeInitial pending
freshChain <- case resumed of Initialised c -> pure c; _ -> fail "initial resume"
check "fresh initial result" (snapshotSites (chainSnapshot freshChain) == [[0]] &&
snapshotResult (chainSnapshot clean) == snapshotResult (chainSnapshot freshChain) &&
chainSources clean == chainSources freshChain)
first <- transition healthy clean
substituted <- case first of
Transitioned c record | decision record == Accepted -> pure c
_ -> fail "first substitution not accepted"
cleanStep <- transition healthy substituted
retryStep <- transition retrying substituted
nextPending <- case retryStep of
TransitionInterrupted (CallbackInterrupted "wait") _ p -> pure p
_ -> fail "transition suspension"
retried <- resumeTransition nextPending
case (cleanStep, retried) of
(Transitioned expected expectedRecord, Transitioned actual actualRecord) ->
check "fresh retry after substitution" (snapshotSites (chainSnapshot actual) == [[0]] &&
snapshotResult (chainSnapshot expected) == snapshotResult (chainSnapshot actual) &&
chainSources expected == chainSources actual && expectedRecord == actualRecord)
_ -> fail "transition retry failed"
putStrLn "fresh retries agree before and after substitution"