packages feed

lazyppl-singlesite-0.2.0: test/SiteDiscovery.hs

module Main where

import Control.DeepSeq (force)
import Control.Exception (SomeException, evaluate, try)
import Control.Monad (forM_)
import Control.Monad.Trans.Writer (WriterT(..))
import Data.IORef (newIORef, atomicModifyIORef', readIORef, writeIORef)
import Data.List (nub, sort)
import Data.Monoid (Product(..))
import GHC.Exts.Heap (Closure, GenClosure(..), asBox, getBoxedClosureData)
import GHC.Float (castDoubleToWord64, castWord64ToDouble)
import Data.Word (Word64)
import GHC.Stats (getRTSStats, gcs)
import LazyPPL (Meas(..), Prob(..), Tree(..), randomTree)
import LazyPPL.SingleSite.Hooks
import qualified LazyPPL.SingleSite.Internal as S
import System.Mem (performGC)
import System.Random (mkStdGen)
import Test.QuickCheck
import Test.QuickCheck.Random (mkQCGen)
import Test.Tasty (TestTree, defaultIngredients, defaultMain, inOrderTestGroup, localOption)
import Test.Tasty.HUnit (assertBool, testCase)
import Test.Tasty.Options (OptionSet, lookupOption, singleOption)
import Test.Tasty.QuickCheck (QuickCheckReplay(..), QuickCheckTests(..), testProperty)
import Test.Tasty.Runners (parseOptions)

at :: [Int] -> Tree -> Double
at [] (Tree x _) = x
at (i:is) (Tree _ ts) = at is (ts !! i)

-- Compare the actual traversal with GHC's uncached decoder on the same
-- evaluated tree. Both traversals run without an intervening collection.
sameSites :: Property
sameSites = forAll arbitrary $ \seed ->
  forAll (listOf1 (resize 4 (listOf (chooseInt (0,5))))) $ \paths -> ioProperty $ do
    let tree = randomTree (mkStdGen seed)
    forM_ paths (evaluate . (`at` tree))
    performGC
    before <- getRTSStats
    cached <- S.trunc tree >>= evaluate . force . S.getSites
    plain <- S.helperT getBoxedClosureData (asBox tree) >>= evaluate . force . S.getSites
    after <- getRTSStats
    let expected = sort (nub paths)
        found = sort (map reverse cached)
    pure $ counterexample (show (seed,paths,cached,plain,gcs before,gcs after)) $
      found === expected .&&. cached === plain .&&. gcs before === gcs after

gcDuringTraversal :: IO Bool
gcDuringTraversal = do
  let tree = randomTree (mkStdGen 171)
      paths = [[0], [2,1]]
  forM_ paths (evaluate . (`at` tree))
  performGC
  before <- S.trunc tree >>= evaluate . force . map reverse . S.getSites
  collected <- newIORef False
  indirect <- newIORef False
  let inspect box = do
        closure <- getBoxedClosureData box
        case closure of
          IndClosure {} -> writeIORef indirect True
          ConstrClosure {name = "Tree"} -> do
            first <- atomicModifyIORef' collected (\seen -> (True, not seen))
            if first then performGC else pure ()
          _ -> pure ()
        pure closure
  during <- S.helperT inspect (asBox tree) >>= evaluate . force . map reverse . S.getSites
  performGC
  after <- S.trunc tree >>= evaluate . force . map reverse . S.getSites
  happened <- readIORef collected
  observedIndirection <- readIORef indirect
  putStrLn ("GC traversal observed an indirection: " ++ show observedIndirection)
  pure (happened && all ((== paths) . sort) [before, during, after])

acceptedSubstitution :: IO Bool
acceptedSubstitution = do
  let paths = [[0], [2,1]]
      model = Meas (WriterT (Prob (\tree -> ((at [0] tree, at [2,1] tree), Product 1))))
  evaluated <- newIORef Nothing
  let recordTree fresh = do
        result <- pureEvaluator model fresh
        case result of
          Complete pair@(tree, _) -> writeIORef evaluated (Just tree) >> pure (Complete pair)
          _ -> pure result
  kernel <- either fail pure (mkKernel 0 recordTree uniformSites)
    :: IO (Kernel String (Double, Double))
  begun <- initialise kernel (mkStdGen 173)
  case begun of
    Initialised start -> do
      result <- transition kernel start
      case result of
        Transitioned next record -> do
          tree <- readIORef evaluated >>= maybe (fail "candidate tree was not recorded") pure
          before <- S.trunc tree >>= evaluate . force . map reverse . S.getSites
          performGC
          after <- S.trunc tree >>= evaluate . force . map reverse . S.getSites
          pure (decision record == Accepted && sort (snapshotSites (chainSnapshot next)) == paths
                && sort before == paths && sort after == paths)
        _ -> pure False
    _ -> pure False

-- A tree node evaluated to its constructor, with its label and its children
-- both unevaluated. The WebAssembly build meets such nodes in the clustering
-- demo; each field here is a call to a function that is not inlined, so it
-- stays a thunk. Nothing at or below the node was demanded, so the traversal
-- finds no site.
{-# NOINLINE opaqueLabel #-}
opaqueLabel :: Int -> Double
opaqueLabel k = fromIntegral k / 7

{-# NOINLINE opaqueChildren #-}
opaqueChildren :: Int -> [Tree]
opaqueChildren k = [lazyNode (k + 1)]

{-# NOINLINE lazyNode #-}
lazyNode :: Int -> Tree
lazyNode k = Tree (opaqueLabel k) (opaqueChildren k)

isThunk :: Closure -> Bool
isThunk ThunkClosure {} = True
isThunk _ = False

-- Labels evaluated to their constructor must decode from the heap payload to
-- the Double whose bits the closure holds. The patterns cover the sign bit
-- alone, zero, both smallest subnormals, the largest finite value of each
-- sign and two ordinary values. Each label and each leaf's children are
-- materialised through NOINLINE calls, so every one is a fresh dynamic
-- closure: a shared literal would be an indirection to a static closure, and
-- a static empty-tail CAF is shortcut to the evaluated [] constructor, which
-- the traversal does not accept. The unentered dynamic thunks are where the
-- traversal stops.
labelBits :: [Word64]
labelBits =
  [ 0x8000000000000000 -- -0.0
  , 0x0000000000000000 -- 0.0
  , 0x0000000000000001 -- 5e-324
  , 0x8000000000000001 -- -5e-324
  , 0x7FEFFFFFFFFFFFFF -- 1.7976931348623157e308
  , 0xFFEFFFFFFFFFFFFF -- -1.7976931348623157e308
  , 0x3FF0000000000000 -- 1.0
  , 0xC045000000000000 -- -42.0
  ]

{-# NOINLINE materialiseLabel #-}
materialiseLabel :: Word64 -> Double
materialiseLabel w = castWord64ToDouble w

{-# NOINLINE lazyChildren #-}
lazyChildren :: Word64 -> [Tree]
lazyChildren _ = []

{-# NOINLINE patternTree #-}
patternTree :: [Word64] -> Tree
patternTree (x:xs) =
  Tree (materialiseLabel x)
    (map (\y -> Tree (materialiseLabel y) (lazyChildren y)) xs)
patternTree [] = Tree (materialiseLabel 0) (lazyChildren 0)

ptreeLabels :: S.PTree -> [Maybe Double]
ptreeLabels (S.PTree label children) = label : concatMap foldChildren children
  where
    foldChildren Nothing = []
    foldChildren (Just t) = ptreeLabels t

decodedLabelsKeepTheirBits :: IO Bool
decodedLabelsKeepTheirBits = do
  let tree = patternTree labelBits
      leaves = drop 1 labelBits
  tree' <- evaluate tree
  evaluate (at [] tree')
  forM_ (zip [0 ..] leaves) (\(i, _) -> evaluate (at [i] tree'))
  cached <- S.trunc tree'
  plain <- S.helperT getBoxedClosureData (asBox tree')
  let bits = map (fmap castDoubleToWord64)
      expected = map Just labelBits
      ok = bits (ptreeLabels cached) == expected
        && bits (ptreeLabels plain) == expected
  putStrLn $ (if ok then "PASS" else "FAIL")
    ++ " decoded labels keep their bits: cached "
    ++ show (bits (ptreeLabels cached)) ++ ", plain "
    ++ show (bits (ptreeLabels plain)) ++ ", expected " ++ show expected
  pure ok

unevaluatedNode :: IO Bool
unevaluatedNode = do
  node@(Tree label children) <- evaluate (lazyNode 3)
  shapes <- mapM getBoxedClosureData [asBox label, asBox children]
  cached <- try (S.trunc node >>= evaluate . force . S.getSites)
  plain <- try (S.helperT getBoxedClosureData (asBox node) >>= evaluate . force . S.getSites)
  let shown = either (\e -> "an error: " ++ show (e :: SomeException)) show
      ok = all isThunk shapes && either (const False) null cached && either (const False) null plain
  putStrLn $ (if ok then "PASS" else "FAIL") ++ " a node with an unevaluated label and children has no site: fields "
    ++ show (map isThunk shapes) ++ " thunks; trunc gives " ++ shown cached ++ "; helperT gives " ++ shown plain
  pure ok

main :: IO ()
main = do
  options <- parseOptions defaultIngredients (checks mempty)
  defaultMain (checks options)

checks :: OptionSet -> TestTree
checks options = inOrderTestGroup "site discovery"
  [ testCase "unevaluated node" $
      unevaluatedNode >>= assertBool "A node with an unevaluated label and children was not traversed"
  , testCase "decoded labels keep their bits" $
      decodedLabelsKeepTheirBits >>= assertBool "An evaluated label did not decode to the same Double"
  , testCase "known paths across garbage collection" $
      gcDuringTraversal >>= assertBool "Known paths changed across garbage collection"
  , testCase "known sites after accepted substitution" $
      acceptedSubstitution >>= assertBool "Accepted substitution changed the known sites"
  , localOption (lookupOption (singleOption (QuickCheckTests 200) <> options) :: QuickCheckTests) $
      localOption (lookupOption (singleOption (QuickCheckReplay (mkQCGen 20261026, 0)) <> options) :: QuickCheckReplay) $
        testProperty "seeded site discovery" sameSites
  ]