packages feed

lazyppl-singlesite 0.1.0 → 0.2.0

raw patch · 12 files changed

+2017/−74 lines, 12 filesdep +statisticsdep +tastydep +tasty-hunitPVP ok

version bump matches the API change (PVP)

Dependencies added: statistics, tasty, tasty-hunit, tasty-quickcheck, vector

API changes (from Hackage documentation)

- LazyPPL.SingleSite.Internal: instance GHC.Show.Show LazyPPL.SingleSite.Internal.PTree
+ LazyPPL.SingleSite.Hooks: Accepted :: Decision
+ LazyPPL.SingleSite.Hooks: CallbackFailed :: e -> KernelError e
+ LazyPPL.SingleSite.Hooks: CallbackInterrupted :: e -> KernelError e
+ LazyPPL.SingleSite.Hooks: Complete :: a -> Completion e a
+ LazyPPL.SingleSite.Hooks: Failed :: e -> Completion e a
+ LazyPPL.SingleSite.Hooks: InitialFailed :: KernelError e -> InitialResult e g a
+ LazyPPL.SingleSite.Hooks: InitialInterrupted :: KernelError e -> PendingInitial e g a -> InitialResult e g a
+ LazyPPL.SingleSite.Hooks: Initialised :: Chain g a -> InitialResult e g a
+ LazyPPL.SingleSite.Hooks: InvalidCompletedResult :: String -> KernelError e
+ LazyPPL.SingleSite.Hooks: InvalidCompletedWeight :: Double -> KernelError e
+ LazyPPL.SingleSite.Hooks: InvalidSelection :: Site -> KernelError e
+ LazyPPL.SingleSite.Hooks: InvalidSiteLaw :: String -> KernelError e
+ LazyPPL.SingleSite.Hooks: NoActiveSite :: ProposalKind
+ LazyPPL.SingleSite.Hooks: RefreshAll :: ProposalKind
+ LazyPPL.SingleSite.Hooks: Rejected :: Decision
+ LazyPPL.SingleSite.Hooks: ResampleSite :: Site -> ProposalKind
+ LazyPPL.SingleSite.Hooks: Stayed :: Decision
+ LazyPPL.SingleSite.Hooks: Suspend :: e -> IO (Completion e a) -> Completion e a
+ LazyPPL.SingleSite.Hooks: SynchronousFailure :: String -> KernelError e
+ LazyPPL.SingleSite.Hooks: TransitionFailed :: KernelError e -> Chain g a -> TransitionResult e g a
+ LazyPPL.SingleSite.Hooks: TransitionInterrupted :: KernelError e -> Chain g a -> PendingTransition e g a -> TransitionResult e g a
+ LazyPPL.SingleSite.Hooks: TransitionRecord :: Int -> ProposalKind -> Decision -> Maybe Rational -> Maybe Rational -> Maybe Double -> Maybe Rational -> Double -> Maybe Double -> TransitionRecord
+ LazyPPL.SingleSite.Hooks: Transitioned :: Chain g a -> TransitionRecord -> TransitionResult e g a
+ LazyPPL.SingleSite.Hooks: [acceptanceUniform] :: TransitionRecord -> Maybe Double
+ LazyPPL.SingleSite.Hooks: [candidateLogWeight] :: TransitionRecord -> Maybe Double
+ LazyPPL.SingleSite.Hooks: [decision] :: TransitionRecord -> Decision
+ LazyPPL.SingleSite.Hooks: [forwardSiteMass] :: TransitionRecord -> Maybe Rational
+ LazyPPL.SingleSite.Hooks: [logAcceptance] :: TransitionRecord -> Maybe Rational
+ LazyPPL.SingleSite.Hooks: [previousLogWeight] :: TransitionRecord -> Double
+ LazyPPL.SingleSite.Hooks: [proposalKind] :: TransitionRecord -> ProposalKind
+ LazyPPL.SingleSite.Hooks: [reverseSiteMass] :: TransitionRecord -> Maybe Rational
+ LazyPPL.SingleSite.Hooks: [transitionIndex] :: TransitionRecord -> Int
+ LazyPPL.SingleSite.Hooks: acceptanceLog :: Double -> Double -> Rational -> Rational -> Maybe Rational
+ LazyPPL.SingleSite.Hooks: accepts :: Double -> Maybe Rational -> Bool
+ LazyPPL.SingleSite.Hooks: chainSnapshot :: Chain g a -> Snapshot a
+ LazyPPL.SingleSite.Hooks: chainSources :: Chain g a -> (g, g, [(Site, Double)])
+ LazyPPL.SingleSite.Hooks: chainTransitions :: Chain g a -> Int
+ LazyPPL.SingleSite.Hooks: data Chain g a
+ LazyPPL.SingleSite.Hooks: data Completion e a
+ LazyPPL.SingleSite.Hooks: data Decision
+ LazyPPL.SingleSite.Hooks: data InitialResult e g a
+ LazyPPL.SingleSite.Hooks: data Kernel e a
+ LazyPPL.SingleSite.Hooks: data KernelError e
+ LazyPPL.SingleSite.Hooks: data PendingInitial e g a
+ LazyPPL.SingleSite.Hooks: data PendingTransition e g a
+ LazyPPL.SingleSite.Hooks: data ProposalKind
+ LazyPPL.SingleSite.Hooks: data SiteLaw
+ LazyPPL.SingleSite.Hooks: data Snapshot a
+ LazyPPL.SingleSite.Hooks: data TransitionRecord
+ LazyPPL.SingleSite.Hooks: data TransitionResult e g a
+ LazyPPL.SingleSite.Hooks: initialise :: (RandomGen g, NFData a) => Kernel e a -> g -> IO (InitialResult e g a)
+ LazyPPL.SingleSite.Hooks: instance GHC.Internal.Classes.Eq LazyPPL.SingleSite.Hooks.Decision
+ LazyPPL.SingleSite.Hooks: instance GHC.Internal.Classes.Eq LazyPPL.SingleSite.Hooks.ProposalKind
+ LazyPPL.SingleSite.Hooks: instance GHC.Internal.Classes.Eq LazyPPL.SingleSite.Hooks.TransitionRecord
+ LazyPPL.SingleSite.Hooks: instance GHC.Internal.Classes.Eq e => GHC.Internal.Classes.Eq (LazyPPL.SingleSite.Hooks.KernelError e)
+ LazyPPL.SingleSite.Hooks: instance GHC.Internal.Show.Show LazyPPL.SingleSite.Hooks.Decision
+ LazyPPL.SingleSite.Hooks: instance GHC.Internal.Show.Show LazyPPL.SingleSite.Hooks.ProposalKind
+ LazyPPL.SingleSite.Hooks: instance GHC.Internal.Show.Show LazyPPL.SingleSite.Hooks.TransitionRecord
+ LazyPPL.SingleSite.Hooks: instance GHC.Internal.Show.Show e => GHC.Internal.Show.Show (LazyPPL.SingleSite.Hooks.KernelError e)
+ LazyPPL.SingleSite.Hooks: mkKernel :: Rational -> Evaluator e a -> SiteSelector e a -> Either String (Kernel e a)
+ LazyPPL.SingleSite.Hooks: mkSiteLaw :: [(Site, Rational)] -> Either String SiteLaw
+ LazyPPL.SingleSite.Hooks: mkSiteLawUnchecked :: (forall g. RandomGen g => g -> (Site, g)) -> [(Site, Rational)] -> Either String SiteLaw
+ LazyPPL.SingleSite.Hooks: pureEvaluator :: Meas a -> Evaluator e a
+ LazyPPL.SingleSite.Hooks: resumeInitial :: PendingInitial e g a -> IO (InitialResult e g a)
+ LazyPPL.SingleSite.Hooks: resumeTransition :: PendingTransition e g a -> IO (TransitionResult e g a)
+ LazyPPL.SingleSite.Hooks: siteMass :: SiteLaw -> Site -> Rational
+ LazyPPL.SingleSite.Hooks: snapshotResult :: Snapshot a -> (a, Product (Log Double))
+ LazyPPL.SingleSite.Hooks: snapshotSites :: Snapshot a -> [Site]
+ LazyPPL.SingleSite.Hooks: transition :: (RandomGen g, NFData a) => Kernel e a -> Chain g a -> IO (TransitionResult e g a)
+ LazyPPL.SingleSite.Hooks: type Evaluator e a = TreeFactory -> IO Completion e (Tree, (a, Product Log Double))
+ LazyPPL.SingleSite.Hooks: type Site = [Int]
+ LazyPPL.SingleSite.Hooks: type SiteSelector e a = Snapshot a -> IO Completion KernelError e SiteLaw
+ LazyPPL.SingleSite.Hooks: type TreeFactory = IO Tree
+ LazyPPL.SingleSite.Hooks: uniformSites :: SiteSelector e a
+ LazyPPL.SingleSite.Internal: LocalStep :: Site -> g -> Double -> a -> decision -> LocalStep g a decision
+ LazyPPL.SingleSite.Internal: NoLocalSite :: LocalStep g a decision
+ LazyPPL.SingleSite.Internal: data LocalStep g a decision
+ LazyPPL.SingleSite.Internal: doubleFromWords :: [Word] -> IO Double
+ LazyPPL.SingleSite.Internal: instance GHC.Internal.Show.Show LazyPPL.SingleSite.Internal.PTree
+ LazyPPL.SingleSite.Internal: localStepWith :: (Monad m, RandomGen g) => Maybe (g -> m (Site, g, selection)) -> (Site -> g -> Double -> m a) -> (Site -> selection -> Double -> a -> m decision) -> g -> m (LocalStep g a decision)

Files

ChangeLog.md view
@@ -1,11 +1,53 @@ # Changelog for lazyppl-singlesite +## 0.2.0++- Site discovery follows blackholes and indirections and inspects evaluated+  tree constructors, boxed `Double` labels and list cells. A `Double` label is+  decoded from its machine words with `castWord64ToDouble` on a 64-bit platform.+- A module compiled with both `-fno-cse` and `-fno-full-laziness` can be+  miscompiled by GHC (see GHC issue #27886); add `-fno-float-in` to such a+  module. The tests also pass for a client built with plain `-O2`. Tested on+  Linux x86_64 with GHC 9.6.7, 9.12.4 and 9.14.1 and `lazyppl-1.1.0.1`.+- The guided kernel's invariance argument assumes ideal independent prior+  draws and reproducible evaluation. Finite 52-bit midpoint acceptance labels+  and rounded logarithms mean that argument does not establish exact+  machine-level invariance.+- Matrix checks compare assessed probabilities with rational references;+  separate frequency checks sample transitions from the actual random source.+- `mkSiteLaw` derives its draw from the supplied masses; `mkSiteLawUnchecked`+  accepts an explicitly supplied draw. `Completion` includes terminal `Failed`,+  reported through `InitialFailed` or `TransitionFailed`. Permanent callback+  errors use `CallbackFailed`, distinct from retryable `CallbackInterrupted`.+- Selectors return `KernelError` values directly, including `InvalidSiteLaw`+  for an empty uniform site law. A returned `Failed` is permanent; a thrown+  synchronous exception suspends, and an explicit resume calls the selector+  again. Callers must stop resuming a deterministic exception.+- A synchronous failure while drawing a site or its proposal and acceptance+  labels suspends the transition and retains the current chain for resumption.+- Add explicit completed evaluators, deterministic site-selection laws and+  transition records in `LazyPPL.SingleSite.Hooks`.+- Refactor the existing local transition driver so legacy `mhStep` and the+  completed path share source selection, proposal and decision sequencing.+- Complete each pass on a fresh heap of the same logical source, and discover+  sites only on the successful heap. Mutation recipes retain their source+  generators so earlier forced labels are not inserted into the new heap.+- A typed interruption retains the accepted snapshot and exact pending attempt.+  Resuming completes that attempt before a proposal generator can advance.+- A completed rejection retains the actual accepted snapshot. State-dependent+  guides are reassessed at the candidate, including zero reverse support.+- Add a fixed-probability whole-prior-tree `RefreshAll` component for coordinates+  excluded by a local site guide.+- Existing `mh1` keeps its API, arithmetic and source order. The new hooks qualify finite forceable outputs+  of referentially stable programs; they do not repair hidden mutable core values.+- Depends on `lazyppl ==1.1.*`, as before.+ ## 0.1.0  - The single-site Metropolis-Hastings sampler `mh1` was part of `lazyppl` 1.0.1. From `lazyppl` 1.1.0 it is in this package, so that `lazyppl` no longer depends on `ghc-heap`. - Import `LazyPPL.SingleSite` as before and depend on `lazyppl-singlesite`, which works with `lazyppl ==1.1.*`. - `lazyppl-singlesite` depends on `ghc-heap >=9.6.1 && <9.15` and is tested with GHC 9.6.7, 9.12.4 and 9.14.1.-- `mh1` changes one random choice per step. It finds the random choices that a model has evaluated by inspecting GHC's heap, so garbage collection can change which ones it finds.+- `mh1` changes one random choice per step. It finds the random choices that a model has evaluated by inspecting GHC's heap, so garbage collection can change which ones it finds. A known limit: `mh1` evaluates each result to normal form, so for an infinite result, such as an infinite list, it yields the initial draw and then never yields the next pair. `mh` from `LazyPPL.Inference.Run` has no such limit and is the general recommendation. - `mh1` rejects a proposal when the reverse site is absent from the proposed tree's evaluated sites. Otherwise, while the current weight is zero, it accepts every proposal. - `mh1` accepts a move when its uniform draw is below the acceptance ratio. It used to accept on equality, so a uniform draw of 0 accepted a move to weight 0. - `mh1` draws its proposed labels from the open interval (0,1) and takes its generator from `newStdGen`. It raises an error when a total log weight overflows to positive infinity.
lazyppl-singlesite.cabal view
@@ -5,10 +5,14 @@ -- see: https://github.com/sol/hpack  name:           lazyppl-singlesite-version:        0.1.0+version:        0.2.0 synopsis:       Single-site Metropolis-Hastings for LazyPPL description:    Single-site Metropolis-Hastings for LazyPPL. Import LazyPPL.SingleSite                 to use mh1. The sampler discovers evaluated random choices through GHC's heap.+                A known limit: mh1 evaluates each result to normal form, so for an infinite+                result, such as an infinite list, it yields the initial draw and then never+                yields the next pair. mh from LazyPPL.Inference.Run has no such limit and is+                the general recommendation. category:       Statistics stability:      experimental homepage:       https://lazyppl-team.github.io/@@ -34,6 +38,7 @@   exposed-modules:       LazyPPL.SingleSite       LazyPPL.SingleSite.Internal+      LazyPPL.SingleSite.Hooks   hs-source-dirs:       src   build-depends:@@ -47,6 +52,51 @@     , transformers >=0.6.1.0 && <0.7   default-language: Haskell2010 +test-suite completed-hooks-test+  type: exitcode-stdio-1.0+  main-is: CompletedHooks.hs+  other-modules:+      FreshRetry+      GuidedReference+  hs-source-dirs:+      test+  ghc-options: -Wall -O2+  build-depends:+      base >=4.18.3.0 && <4.23+    , containers >=0.6.7 && <0.9+    , deepseq >=1.4.8.1 && <1.6+    , ghc-heap >=9.6.1 && <9.15+    , lazyppl ==1.1.*+    , lazyppl-singlesite+    , log-domain >=0.13.2 && <0.14+    , random >=1.3.1 && <1.4+    , statistics >=0.16.2 && <0.17+    , transformers >=0.6.1.0 && <0.7+    , vector >=0.12 && <0.14+  default-language: Haskell2010++test-suite plain-optimised-client-test+  type: exitcode-stdio-1.0+  main-is: PlainOptimisedClient.hs+  other-modules:+      GuidedReference+  hs-source-dirs:+      test+  ghc-options: -O2+  build-depends:+      base >=4.18.3.0 && <4.23+    , containers >=0.6.7 && <0.9+    , deepseq >=1.4.8.1 && <1.6+    , ghc-heap >=9.6.1 && <9.15+    , lazyppl ==1.1.*+    , lazyppl-singlesite+    , log-domain >=0.13.2 && <0.14+    , random >=1.3.1 && <1.4+    , statistics >=0.16.2 && <0.17+    , transformers >=0.6.1.0 && <0.7+    , vector >=0.12 && <0.14+  default-language: Haskell2010+ test-suite reverse-support-test   type: exitcode-stdio-1.0   main-is: Api.hs@@ -63,6 +113,8 @@     , lazyppl-singlesite     , log-domain >=0.13.2 && <0.14     , random >=1.3.1 && <1.4+    , tasty ==1.5.5+    , tasty-hunit ==0.10.2     , transformers >=0.6.1.0 && <0.7   default-language: Haskell2010 @@ -82,5 +134,8 @@     , lazyppl-singlesite     , log-domain >=0.13.2 && <0.14     , random >=1.3.1 && <1.4+    , tasty ==1.5.5+    , tasty-hunit ==0.10.2+    , tasty-quickcheck ==0.11.1     , transformers >=0.6.1.0 && <0.7   default-language: Haskell2010
src/LazyPPL/SingleSite.hs view
@@ -5,6 +5,13 @@ after that, we randomly change one site (a node in the random tree), and then accept or reject the change. If rejected, we repeat the previous pair. +@mh1@ evaluates each result in full (with @rnf@, hence the @NFData@+constraint) to find the sites that the result depends on. A result must+therefore have a finite normal form. For an infinite result, such as an+infinite list, @mh1@ yields the initial draw and then never yields the next+pair. Use @mh@ from "LazyPPL.Inference.Run" for such models. It has no such+limit, and it is the general-purpose sampler.+ Use 'drop' for burn-in and @LazyPPL.every@ for thinning. -} module LazyPPL.SingleSite (mh1) where 
+ src/LazyPPL/SingleSite/Hooks.hs view
@@ -0,0 +1,468 @@+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | Explicit completion and proposal hooks for single-site inference.+--+-- Evaluation must be referentially stable on its supplied Tree and return a+-- finite, forceable result. A suspended callback is resumed before a transition+-- can commit. Hidden mutable core values are not made replay-safe by this API.+-- An exception while forcing a completed result is a terminal+-- 'InvalidCompletedResult', since forcing that same result again cannot retry+-- the evaluator.+--+-- With independent ideal prior draws, reproducible evaluation, and matching+-- site draws and masses, the local and fixed-probability refresh kernels+-- preserve the target distribution. The implementation uses finite 52-bit+-- midpoint acceptance labels and rounded logarithms, so exact machine-level+-- invariance does not follow from that ideal-randomness argument.+--+-- Site discovery inspects evaluated 'Tree' constructors, boxed 'Double'+-- labels and evaluated list cells; unevaluated labels and children are not+-- sites. It follows blackholes and indirections. Other heap representations+-- are not covered. A 'Double' label is decoded from its machine words with+-- @castWord64ToDouble@ on a 64-bit platform; the decoder is tested on Linux+-- x86_64.+--+-- A module compiled with both @-fno-cse@ and @-fno-full-laziness@ can be+-- miscompiled by GHC (see GHC issue #27886); add @-fno-float-in@ to such a+-- module. The tests also pass for a client built with plain @-O2@. Tested on+-- Linux x86_64 with GHC 9.6.7, 9.12.4 and 9.14.1 and lazyppl 1.1.0.1.+module LazyPPL.SingleSite.Hooks+  ( Site, Completion (..), TreeFactory, Evaluator, SiteSelector+  , SiteLaw, mkSiteLaw, mkSiteLawUnchecked, siteMass, uniformSites+  , Kernel, mkKernel, pureEvaluator+  , Snapshot, snapshotResult, snapshotSites+  , Chain, chainSnapshot, chainSources, chainTransitions+  , KernelError (..), ProposalKind (..), Decision (..), TransitionRecord (..)+  , InitialResult (..), PendingInitial, initialise, resumeInitial+  , TransitionResult (..), PendingTransition, transition, resumeTransition+  , acceptanceLog, accepts+  ) where++import Control.DeepSeq (NFData, force)+import Control.Exception+  ( SomeException, SomeAsyncException, displayException, evaluate+  , fromException, tryJust )+import Control.Monad.Trans.Writer (runWriterT)+import Control.Monad.Trans.Cont (ContT (..))+import Data.IORef (newIORef, readIORef)+import qualified Data.Map.Strict as Map+import qualified Data.Map.Lazy as Substitution+import Data.Monoid (Product (..))+import Data.Ratio (denominator, numerator)+import LazyPPL (Meas (..), Tree, randomTree, runProb)+import LazyPPL.Internal.Sampler (randomLabel)+import LazyPPL.SingleSite.Internal+  ( Site, PTree, LocalStep (..), localStepWith+  , getSites, mutateNodes, trunc )+import Numeric.Log (Log, ln)+import System.Random (RandomGen, split, uniformR)++-- | A callback may suspend with an explicit continuation on the same request+-- and source. Calling the continuation is an explicit retry, never a rejection.+-- A permanent failure has no continuation and leaves the chain unchanged.+data Completion e a+  = Complete a+  | Suspend e (IO (Completion e a))+  | Failed e++-- Each call must allocate a fresh heap for the same logical source. An+-- evaluator returns the exact successful heap, never one retained from a+-- failed pass. This is needed for completed used-site discovery.+type TreeFactory = IO Tree+type Evaluator e a = TreeFactory+  -> IO (Completion e (Tree, (a, Product (Log Double))))++-- | The selector is a deterministic function of the completed snapshot.+-- Its IO may complete immutable oracle requests; it must not draw unrecorded+-- auxiliary randomness or turn a backend failure into a different law.+-- A returned 'Failed' is permanent. A thrown synchronous exception suspends+-- the attempt; each explicit resume calls the selector again, so callers must+-- stop resuming a deterministic failure instead of retrying it indefinitely.+type SiteSelector e a = Snapshot a -> IO (Completion (KernelError e) SiteLaw)++-- The ordinary constructor derives the sampler from the assessed masses.+data SiteLaw = SiteLaw+  (forall g. RandomGen g => g -> (Site, g))+  (Map.Map Site Rational)++mkSiteLaw :: [(Site, Rational)] -> Either String SiteLaw+mkSiteLaw entries = mkSiteLawUnchecked draw entries+  where+    common = foldr lcm 1 (map (denominator . snd) entries)+    weighted = [(site, numerator (mass * fromInteger common)) | (site, mass) <- entries]+    draw generator =+      let (ticket, next) = uniformR (1, common) generator+          pick _ [] = error "mkSiteLaw: validated masses do not cover the draw"+          pick n ((site, weight):rest)+            | n <= weight = site+            | otherwise = pick (n - weight) rest+      in (pick ticket weighted, next)++-- State-dependent guides may supply an externally derived sampler. Its author+-- must ensure that sampler and supplied masses describe the same law.+mkSiteLawUnchecked :: (forall g. RandomGen g => g -> (Site, g))+                   -> [(Site, Rational)] -> Either String SiteLaw+mkSiteLawUnchecked draw entries+  | null entries = Left "empty site law"+  | length sites /= Map.size masses = Left "duplicate site"+  | any (any (< 0)) sites = Left "negative site coordinate"+  | any ((< 0) . snd) entries = Left "negative site mass"+  | sum (map snd entries) /= 1 = Left "site masses do not sum to one"+  | any losesLog entries = Left "positive site mass is lost by binary64 logarithm conversion"+  | otherwise = Right (SiteLaw draw masses)+  where+    sites = map fst entries+    masses = Map.fromList entries+    losesLog (_, mass)+      | mass == 0 = False+      | otherwise = let value = log (fromRational mass :: Double)+                    in isNaN value || isInfinite value++siteMass :: SiteLaw -> Site -> Rational+siteMass (SiteLaw _ masses) site = Map.findWithDefault 0 site masses++-- | Reuse the existing maintained discrete selector, with its assessed mass.+uniformSites :: SiteSelector e a+uniformSites snapshot =+  let sites = snapshotSites snapshot+      mass = 1 / fromIntegral (length sites)+  in case mkSiteLaw [(site, mass) | site <- sites] of+       Right law -> pure (Complete law)+       Left message -> pure (Failed (InvalidSiteLaw message))++data Kernel e a = Kernel+  { evaluator :: Evaluator e a+  , selector :: SiteSelector e a+  , refreshProbability :: Rational+  }++-- | The fixed refresh probability is independent of the current state.+-- A positive value provides a whole-prior-tree proposal, including currently+-- hidden branches. It does not prove posterior connectivity or finite runtime.+mkKernel :: Rational -> Evaluator e a -> SiteSelector e a+         -> Either String (Kernel e a)+mkKernel probability evaluateTree selectSite+  | probability < 0 || probability > 1 = Left "refresh probability outside [0,1]"+  | otherwise = Right (Kernel evaluateTree selectSite probability)++pureEvaluator :: Meas a -> Evaluator e a+pureEvaluator (Meas model) fresh = do+  tree <- fresh+  pure (Complete (tree, runProb (runWriterT model) tree))++-- Keep the actual evaluated tree and value/weight pair, not an extensional+-- reconstruction. Rejection returns this same Snapshot object.+data Snapshot a = Snapshot Tree (a, Product (Log Double)) PTree [Site]++snapshotResult :: Snapshot a -> (a, Product (Log Double))+snapshotResult (Snapshot _ result _ _) = result++-- A selector sees only the completed result and its revealed site paths; it+-- cannot use this interface to demand additional labels from the latent Tree.+snapshotSites :: Snapshot a -> [Site]+snapshotSites (Snapshot _ _ _ sites) = sites++data Chain g a = Chain+  { chainSnapshot :: Snapshot a+  , chainTreeSeed :: g+  , chainSubstitution :: Map.Map Site (g, Double)+  , chainProposalSeed :: !g+  , chainTransitions :: !Int+  }++-- | Source identity for finite reproducibility records. Sites are root-to-leaf.+-- This is not serialization of arbitrary suspended callbacks or model values.+chainSources :: Chain g a -> (g, g, [(Site, Double)])+chainSources chain =+  (chainTreeSeed chain, chainProposalSeed chain,+   [(site, value) | (site, (_, value)) <- Map.toAscList (chainSubstitution chain)])++-- Rebuild using the established randomTree/mutateNodes implementation. Read+-- the recipe inside each invocation through an IO allocation boundary rather+-- than supplying a closed pure Tree expression. Mutation recipes regenerate the+-- same label; they do not insert a previously forced Double into the new heap.+-- This is compiler-qualified by the optimized missed-request/demand controls,+-- not a language-level theorem that a pure wrapper guarantees fresh objects.+materialiseTree :: RandomGen g => g -> Map.Map Site (g, Double) -> TreeFactory+materialiseTree seed edits = do+  source <- newIORef (seed, edits)+  (freshSeed, freshEdits) <- readIORef source+  let substitutions = Substitution.map (\(generator, _) -> fst (randomLabel generator)) freshEdits+  evaluate (mutateNodes (randomTree freshSeed) substitutions)+{-# NOINLINE materialiseTree #-}++data KernelError e+  = CallbackInterrupted e+  | CallbackFailed e+  | InvalidCompletedResult String+  | InvalidCompletedWeight Double+  | InvalidSiteLaw String+  | InvalidSelection Site+  | SynchronousFailure String+  deriving (Eq, Show)++data ProposalKind = ResampleSite Site | RefreshAll | NoActiveSite+  deriving (Eq, Show)++data Decision = Accepted | Rejected | Stayed+  deriving (Eq, Show)++-- | Site masses include state-dependent selection. The fixed branch-mixture+-- probability cancels for each reversible component. A fresh uniform label+-- and a whole-prior-tree refresh each cancel against their prior source law.+data TransitionRecord = TransitionRecord+  { transitionIndex :: Int+  , proposalKind :: ProposalKind+  , decision :: Decision+  , forwardSiteMass :: Maybe Rational+  , reverseSiteMass :: Maybe Rational+  , acceptanceUniform :: Maybe Double+  , logAcceptance :: Maybe Rational+  , previousLogWeight :: Double+  , candidateLogWeight :: Maybe Double+  } deriving (Eq, Show)++data InitialResult e g a+  = Initialised (Chain g a)+  | InitialInterrupted (KernelError e) (PendingInitial e g a)+  | InitialFailed (KernelError e)++newtype PendingInitial e g a =+  PendingInitial (IO (InitialResult e g a))++resumeInitial :: PendingInitial e g a -> IO (InitialResult e g a)+resumeInitial (PendingInitial action) = action++data TransitionResult e g a+  = Transitioned (Chain g a) TransitionRecord+  | TransitionInterrupted (KernelError e) (Chain g a) (PendingTransition e g a)+  | TransitionFailed (KernelError e) (Chain g a)++newtype PendingTransition e g a =+  PendingTransition (IO (TransitionResult e g a))++resumeTransition :: PendingTransition e g a -> IO (TransitionResult e g a)+resumeTransition (PendingTransition action) = action++bindCompletion :: IO (Completion e a)+               -> (a -> IO (Completion e b)) -> IO (Completion e b)+bindCompletion action next = do+  result <- action+  case result of+    Complete value -> next value+    Suspend err resume -> pure (Suspend err (bindCompletion resume next))+    Failed err -> pure (Failed err)++-- Use the maintained continuation transformer to instantiate the shared+-- generic local step. Suspension closes over the continuation of that same+-- step; it does not restart selection or consume another random label.+awaitCompletion :: IO (Completion e a) -> ContT (Completion e r) IO a+awaitCompletion action = ContT (bindCompletion action)++mapCallback :: IO (Completion e a) -> IO (Completion (KernelError e) a)+mapCallback action = protect (do+  result <- action+  case result of+    Complete value -> evaluate value >> pure result+    _ -> pure result) `bindCompletion` mapResult+  where+    mapResult (Complete value) = pure (Complete value)+    mapResult (Failed err) = pure (Failed (CallbackFailed err))+    mapResult (Suspend err resume) =+      pure (Suspend (CallbackInterrupted err) (mapCallback resume))++-- Catch synchronous execution/forcing failures only. Cancellation propagates;+-- it never becomes a zero-weight state or a silently rejected proposal.+protect :: IO a -> IO (Completion (KernelError e) a)+protect action = do+  result <- tryJust synchronous action+  case result of+    Right value -> pure (Complete value)+    Left err -> pure (Suspend (SynchronousFailure (displayException err)) (protect action))++synchronous :: SomeException -> Maybe SomeException+synchronous err = case fromException err :: Maybe SomeAsyncException of+  Just _ -> Nothing+  Nothing -> Just err++invalid :: KernelError e -> IO (Completion (KernelError e) a)+invalid err = pure (Failed err)++completeSnapshot :: NFData a => (Tree, (a, Product (Log Double)))+                 -> IO (Completion (KernelError e) (Snapshot a))+completeSnapshot (tree, result) = do+  outcome <- tryJust synchronous (evaluate (force result))+  case outcome of+    Left err -> invalid (InvalidCompletedResult (displayException err))+    Right forced ->+      let weight = ln (getProduct (snd forced))+      in if isNaN weight || (isInfinite weight && weight > 0)+           then invalid (InvalidCompletedWeight weight)+           else protect (do+             partial <- trunc tree+             sites <- evaluate (force (map reverse (getSites partial)))+             pure (Snapshot tree forced partial sites))++evaluateSnapshot :: NFData a => Kernel e a -> TreeFactory+                 -> IO (Completion (KernelError e) (Snapshot a))+evaluateSnapshot kernel fresh =+  mapCallback (evaluator kernel fresh) `bindCompletion` completeSnapshot++initialise :: (RandomGen g, NFData a) => Kernel e a -> g+           -> IO (InitialResult e g a)+initialise kernel source =+  let (treeSeed, proposalSeed) = split source+      finish action = do+        result <- action+        case result of+          Complete snapshot ->+            pure (Initialised (Chain snapshot treeSeed Substitution.empty proposalSeed 0))+          Suspend err resume ->+            pure (InitialInterrupted err (PendingInitial (finish resume)))+          Failed err -> pure (InitialFailed err)+  in finish (evaluateSnapshot kernel (materialiseTree treeSeed Substitution.empty))++snapshotWeight :: Snapshot a -> Double+snapshotWeight = ln . getProduct . snd . snapshotResult++-- | Log of min(1, w'/w * q_reverse/q_forward), represented as an exact rational+-- combination of the supplied finite binary64 logarithms. Nothing is zero+-- acceptance. This avoids overflowing intermediate log differences.+-- The site masses are full marginal probabilities, not selected-component+-- probabilities or normalized importance weights from another inference run.+acceptanceLog :: Double -> Double -> Rational -> Rational -> Maybe Rational+acceptanceLog old new forward reverse+  | forward <= 0 || reverse <= 0 = Nothing+  | isNaN old || isNaN new = Nothing+  | isInfinite new && new < 0 = Nothing+  | isInfinite old && old < 0 = Just 0+  | isInfinite old || isInfinite new = Nothing+  | otherwise = Just (min 0+      (toRational new - toRational old+       + toRational (log (fromRational reverse :: Double))+       - toRational (log (fromRational forward :: Double))))++-- | The core supplies open 52-bit midpoint labels. The comparison is strict,+-- like the original mh1 acceptance convention; no zero label can accept a+-- zero-mass candidate. A fixed seed is execution evidence, not a continuous-+-- randomness stationarity theorem.+accepts :: Double -> Maybe Rational -> Bool+accepts uniformLabel threshold+  | isNaN uniformLabel || uniformLabel <= 0 || uniformLabel >= 1 = False+  | otherwise = maybe False (toRational (log uniformLabel) <) threshold++checkedSelection :: Snapshot a -> SiteLaw+                 -> IO (Completion (KernelError e) SiteLaw)+checkedSelection snapshot law@(SiteLaw _ masses) =+  protect (evaluate (force (Map.toAscList masses))) `bindCompletion` \entries ->+    if any (\(site, mass) -> mass > 0 && site `notElem` snapshotSites snapshot) entries+      then invalid (InvalidSiteLaw "positive selection mass outside active sites")+      else pure (Complete law)++selectLaw :: Kernel e a -> Snapshot a+          -> IO (Completion (KernelError e) SiteLaw)+selectLaw kernel snapshot =+  protectSelector (selector kernel snapshot) `bindCompletion` checkedSelection snapshot++protectSelector :: IO (Completion (KernelError e) a)+                -> IO (Completion (KernelError e) a)+protectSelector action = protect (do+  result <- action+  case result of+    Complete value -> evaluate value >> pure result+    _ -> pure result) `bindCompletion` \result -> case result of+  Complete value -> pure (Complete value)+  Failed err -> pure (Failed err)+  Suspend err resume -> pure (Suspend err (protectSelector resume))++transition :: (RandomGen g, NFData a) => Kernel e a -> Chain g a+           -> IO (TransitionResult e g a)+transition kernel original = finish attempt+  where+    old = chainSnapshot original+    oldWeight = snapshotWeight old+    count = chainTransitions original + 1+    (proposalSource, nextSource) = split (chainProposalSeed original)+    probability = refreshProbability kernel++    finish action = do+      result <- action+      case result of+        Complete (chain, record) -> pure (Transitioned chain record)+        Failed err -> pure (TransitionFailed err original)+        Suspend err resume -> pure+          (TransitionInterrupted err original (PendingTransition (finish resume)))++    -- Only a completed decision commits the proposal generator. The original+    -- chain and the exact suspended attempt remain available on interruption.+    advance snapshot seed substitutions = Chain snapshot seed substitutions nextSource count+    retained = advance old (chainTreeSeed original) (chainSubstitution original)++    record kind verdict forward reverse label threshold proposed =+      TransitionRecord count kind verdict forward reverse label threshold oldWeight proposed++    attempt+      | probability == 0 = local proposalSource+      | probability == 1 = refresh proposalSource+      | otherwise =+          let (ticket, rest) = uniformR (1, denominator probability) proposalSource+          in if ticket <= numerator probability then refresh rest else local rest++    refresh source =+      let (treeSeed, acceptanceSource) = split source+      in protect (evaluate (fst (randomLabel acceptanceSource))) `bindCompletion` \label ->+         evaluateSnapshot kernel (materialiseTree treeSeed Substitution.empty) `bindCompletion` \candidate ->+           let newWeight = snapshotWeight candidate+               threshold = acceptanceLog oldWeight newWeight 1 1+               accepted = accepts label threshold+               next = if accepted then advance candidate treeSeed Substitution.empty else retained+               verdict = if accepted then Accepted else Rejected+           in pure (Complete (next,+                record RefreshAll verdict Nothing Nothing (Just label) threshold (Just newWeight)))++    local source = runContT+      (localStepWith (if null (snapshotSites old) then Nothing else Just choose)+        evaluateCandidate decide source)+      commit+      where+        choose generator = do+          law@(SiteLaw draw _) <- awaitCompletion (selectLaw kernel old)+          let (siteSource, labelSource) = split generator+          site <- awaitCompletion (protect (evaluate (forceSite labelSource (fst (draw siteSource)))))+          if site `notElem` snapshotSites old || siteMass law site <= 0+            then awaitCompletion (invalid (InvalidSelection site))+            else pure (site, labelSource, law)+        evaluateCandidate site labelSource newLabel = do+          let substitutions = Substitution.insert site (labelSource, newLabel)+                (chainSubstitution original)+          candidate <- awaitCompletion (evaluateSnapshot kernel+            (materialiseTree (chainTreeSeed original) substitutions))+          pure (substitutions, candidate)+        decide site law label (_, candidate) = do+          reverse <- if site `notElem` snapshotSites candidate then pure 0 else do+            reverseLaw <- awaitCompletion (selectLaw kernel candidate)+            pure (siteMass reverseLaw site)+          let forward = siteMass law site+              newWeight = snapshotWeight candidate+              threshold = acceptanceLog oldWeight newWeight forward reverse+          pure (forward, reverse, threshold, newWeight, accepts label threshold)+        commit NoLocalSite = pure (Complete+          (retained, record NoActiveSite Stayed Nothing Nothing Nothing Nothing Nothing))+        commit (LocalStep site _ label (substitutions, candidate)+                (forward, reverse, threshold, newWeight, accepted)) =+          let next = if accepted+                then advance candidate (chainTreeSeed original) substitutions+                else retained+              verdict = if accepted then Accepted else Rejected+          in pure (Complete (next,+            record (ResampleSite site) verdict (Just forward) (Just reverse)+              (Just label) threshold (Just newWeight)))++    -- RandomGen need not have NFData. Force both labels the local step will+    -- use while the draw is protected, as well as the complete chosen site.+    forceSite labelSource site =+      let (replacement, next) = randomLabel labelSource+          (acceptance, _) = randomLabel next+      in force site `seq` replacement `seq` acceptance `seq` site+
src/LazyPPL/SingleSite/Internal.hs view
@@ -1,11 +1,11 @@ {-# LANGUAGE MagicHash, UnboxedTuples #-}-{-# LANGUAGE ScopedTypeVariables, CPP- #-}+{-# LANGUAGE ScopedTypeVariables #-} module LazyPPL.SingleSite.Internal where  import LazyPPL import LazyPPL.Internal.Sampler (randomLabel, checkedLogWeight) import Control.Monad.Trans.Writer+import Data.Functor.Identity (Identity (..))  import Data.Monoid import Numeric.Log@@ -17,14 +17,12 @@ import Control.Exception (evaluate)  import System.IO.Unsafe-#ifdef LAZYPPL_BROWSER+ import Foreign.Marshal.Alloc (alloca) import Foreign.Marshal.Array (pokeArray) import Foreign.Ptr (castPtr) import Foreign.Storable (peek, sizeOf)-#else-import Unsafe.Coerce-#endif+import GHC.Float (castWord64ToDouble)   import Data.IORef@@ -62,6 +60,29 @@                -- ^^^^^^^^                 -- Depending on the version of `random` this can be either uniformR or randomR. +-- One local transition driver is shared by the legacy pure sampler and the+-- completed-evaluation interface. The callbacks own evaluation and the exact+-- decision rule; the source order remains site, replacement label, acceptance.+-- The label's generator is retained for interfaces that rebuild fresh heaps+-- without reusing already forced Double objects. It is not advanced on retry.+data LocalStep g a decision+  = NoLocalSite+  | LocalStep Site g Double a decision++localStepWith :: (Monad m, RandomGen g)+              => Maybe (g -> m (Site, g, selection))+              -> (Site -> g -> Double -> m a)+              -> (Site -> selection -> Double -> a -> m decision)+              -> g -> m (LocalStep g a decision)+localStepWith Nothing _ _ _ = pure NoLocalSite+localStepWith (Just select) evaluateCandidate decide source = do+  (site, labelSource, selection) <- select source+  let (newLabel, acceptanceSource) = randomLabel labelSource+      (label, _) = randomLabel acceptanceSource+  candidate <- evaluateCandidate site labelSource newLabel+  verdict <- decide site selection label candidate+  pure (LocalStep site labelSource label candidate verdict)+ mh1 :: forall a. NFData a => Meas a -> IO [(a, Product (Log Double))] mh1 (Meas m) = do     g <- newStdGen@@ -77,30 +98,32 @@ -- current sample with its weight. mhStep :: forall a g. (NFData a, RandomGen g) => Meas a -> (g, g, Subst, PTree, (a, Product (Log Double))) -> (g, g, Subst, PTree, (a, Product (Log Double))) mhStep (Meas m) (treeSeed, seed, sub, ptree, (x,w)) =-            let (seed1, seed2) = split seed-                sites = getSites ptree-            -- A measure that reads no random site has a one-point sample space:-            -- there is no site to mutate, so the chain keeps its sample.-            in if null sites-              then (treeSeed, seed2, sub,  ptree,  (x,w))-              else-                let (seed1', randSite) = (\(x,y) -> (x, reverse y)) $ randomElement seed1 sites-                    (newNode :: Double, seed1'') = randomLabel seed1'-                    (u :: Double, _) = randomLabel seed1''-                    sub' = M.insert randSite newNode sub-                    t' = mutateNodes (randomTree treeSeed) sub'-                    (x',w') = checkedSample (runProb (runWriterT m) t')-                    ptree' = unsafePerformIO $ do { evaluate (rnf x'); evaluate (rnf w'); trunc t' }-                    sites' = getSites ptree'-                    alpha = fromIntegral (length sites) / fromIntegral (length sites')-                          * exp (ln (getProduct w' / getProduct w))-                -- The reverse proposal cannot select a site absent from the proposed tree.-                -- A move is accepted with probability min 1 alpha, so u < alpha; with-                -- u <= alpha, u = 0 would accept a move to weight 0. u is a label, in-                -- (0,1): random's 1 would reject a move with alpha = 1.-                in if reverse randSite `elem` sites' && (getProduct w == 0 || u < alpha)-                  then (treeSeed, seed2, sub', ptree', (x',w'))-                  else (treeSeed, seed2, sub,  ptree,  (x,w))+    let (seed1, seed2) = split seed+        sites = getSites ptree+        select generator =+          let (next, selected) = randomElement generator sites+          in pure (reverse selected, next, ())+        evaluateCandidate site _ newLabel =+          let sub' = M.insert site newLabel sub+              tree = mutateNodes (randomTree treeSeed) sub'+              pair@(x', w') = checkedSample (runProb (runWriterT m) tree)+              partial = unsafePerformIO $ do+                evaluate (rnf x')+                evaluate (rnf w')+                trunc tree+          in pure (sub', partial, pair)+        decide site () label (_, partial, (_, w')) =+          let reverseSites = getSites partial+              alpha = fromIntegral (length sites) / fromIntegral (length reverseSites)+                    * exp (ln (getProduct w' / getProduct w))+          -- Keep the established pure API's arithmetic, strict boundary and+          -- zero-current-weight behavior. The new hooks state their own rule.+          in pure (reverse site `elem` reverseSites && (getProduct w == 0 || label < alpha))+        retained = (treeSeed, seed2, sub, ptree, (x,w))+    in case runIdentity (localStepWith (if null sites then Nothing else Just select) evaluateCandidate decide seed1) of+         NoLocalSite -> retained+         LocalStep _ _ _ (sub', partial, pair) accepted ->+           if accepted then (treeSeed, seed2, sub', partial, pair) else retained  -- A product of valid weights can still overflow to a logarithm of +Infinity. checkedSample :: (a, Product (Log Double)) -> (a, Product (Log Double))@@ -111,6 +134,7 @@   c <- inspect b   case c of     BlackholeClosure _ n -> getGCClosureData inspect n+    IndClosure _ n -> getGCClosureData inspect n     _ -> return c  helperT :: (Box -> IO Closure) -> Box -> IO PTree@@ -126,11 +150,7 @@           -- demanded once the list is evaluated; each field is read on its own,           -- so a node with both fields unevaluated has no site.           label <- case n' of-#ifdef LAZYPPL_BROWSER             ConstrClosure {dataArgs = ds, name = "D#"} -> Just <$> doubleFromWords ds-#else-            ConstrClosure {dataArgs = [d], name = "D#"} -> return (Just (unsafeCoerce d))-#endif             ThunkClosure {} -> return Nothing             SelectorClosure {} -> return Nothing             _ -> missing@@ -140,17 +160,22 @@             _ -> missing           return $ PTree label children     ThunkClosure {} -> return $ PTree Nothing []+    SelectorClosure {} -> ioError (userError "trunc: selector root cannot be inspected without evaluation")+    _ -> ioError (userError ("trunc: unsupported tree closure " ++ show (tipe (info c)))) -#ifdef LAZYPPL_BROWSER--- A Double occupies one 64-bit word or two 32-bit words, in host byte order.+-- | The heap payload of a @D#@ closure, as machine words in host byte order.+-- Where one 'Word' fills the payload, 'castWord64ToDouble' is the documented+-- bit cast; a payload that spans narrower words is reassembled by writing the+-- words and reading the 'Double' back, which keeps the heap's byte order. doubleFromWords :: [Word] -> IO Double doubleFromWords ws-  | length ws * sizeOf (0 :: Word) /= sizeOf (0 :: Double) =-      fail "Unexpected Double heap payload size"-  | otherwise = alloca $ \ptr -> do+  | [w] <- ws, sizeOf (0 :: Word) == sizeOf (0 :: Double) =+      pure (castWord64ToDouble (fromIntegral w))+  | length ws * sizeOf (0 :: Word) == sizeOf (0 :: Double) = alloca $ \ptr -> do       pokeArray (castPtr ptr) ws       peek ptr-#endif+  | otherwise =+      fail "Unexpected Double heap payload size"  helperB :: (Box -> IO Closure) -> Box -> IO [Maybe PTree] helperB inspect b = do@@ -175,6 +200,8 @@             _ -> return $ error $ "Missing case:\n" ++ show n' ++ "\n" ++ show l'     ThunkClosure {} -> return [] +-- | Inspect a tree without evaluating it. A selector root raises an IO error:+-- resolving it could evaluate the selected field and change the observed sites. trunc :: Tree -> IO PTree trunc t = do   cache <- newIORef M.empty
test/Api.hs view
@@ -1,42 +1,65 @@-{-# OPTIONS_GHC -fno-cse -fno-full-laziness #-}--- A constant test tree compiled as a static closure would end in IND_STATIC--- indirections, which the single-site traversal does not read.+{-# OPTIONS_GHC -fno-cse -fno-full-laziness -fno-float-in #-}+-- Avoid the test-module miscompilation matching GHC issue 27886. module Main where  import Control.DeepSeq (rnf)-import Control.Exception (evaluate)-import Control.Monad (unless)+import Control.Exception (IOException, displayException, evaluate, try)+import Control.Monad (forM) import Control.Monad.Trans.Writer (runWriterT) import Data.IORef (newIORef, readIORef)+import Data.List (isInfixOf, nub) import qualified Data.Map as M import Data.Monoid (getProduct) import Data.Word (Word64)-import LazyPPL (Meas(..), randomTree, runProb, sample, score, uniform)-import LazyPPL.Distributions (bernoulli)+import LazyPPL (Meas(..), Tree, randomTree, runProb, sample, score, uniform)+import LazyPPL.Distributions (bernoulli, uniformdiscrete) import LazyPPL.SingleSite (mh1) import qualified LazyPPL.SingleSite.Internal as S import ReverseSupport (reverseSupport) import System.Random (RandomGen(..), SplitGen(..), mkStdGen, setStdGen) import System.Timeout (timeout)+import Test.Tasty (defaultMain, inOrderTestGroup)+import Test.Tasty.HUnit (assertBool, testCase)  main :: IO ()-main = do-  supported <- reverseSupport-  unless supported (fail "single-site rejects proposals without reverse support")-  putStrLn "PASS single-site rejects proposals without reverse support"-  constant <- constantMeasureRepeats-  unless constant (fail "mh1 does not repeat the sample of a site-free measure")-  putStrLn "PASS mh1 repeats the sample of a site-free measure"-  rejected <- zeroWeightMoveRejected-  unless rejected (fail "mh1 accepted a move from positive weight to weight 0")-  putStrLn "PASS mh1 rejects a move from positive weight to weight 0"-  accepted <- ratioOneMoveAccepted-  unless accepted (fail "mh1 rejected a move whose acceptance ratio is 1")-  putStrLn "PASS mh1 accepts a move whose acceptance ratio is 1"-  setStdGen (mkStdGen 23)-  coin <- map fst . take 60000 . drop 1000 <$> mh1 coinModel-  posterior <- posteriorFraction "mh1 coin posterior" coin-  unless posterior (fail "mh1 does not sample the coin posterior")+main = defaultMain $ inOrderTestGroup "single-site"+  [ testCase "reverse support" $ reverseSupport >>= assertBool "single-site rejects proposals without reverse support"+  , testCase "site-free measure" $ constantMeasureRepeats >>= assertBool "mh1 repeats the sample of a site-free measure"+  , testCase "zero-weight move" $ zeroWeightMoveRejected >>= assertBool "mh1 rejects moves from positive weight to weight 0"+  , testCase "ratio-one move" $ ratioOneMoveAccepted >>= assertBool "mh1 accepts moves whose acceptance ratio is 1"+  , testCase "unevaluated selector root" $ do+      seed <- newIORef 7 >>= readIORef+      let record = treeRecord seed+          root = selectedTree record+      _ <- evaluate record+      result <- try (S.trunc root) :: IO (Either IOException S.PTree)+      assertBool "selector roots report their unsupported closure" $+        case result of+          Left err -> "trunc: selector root" `isInfixOf` displayException err+          Right _ -> False+  , testCase "seeded coin posterior" $ do+      setStdGen (mkStdGen 23)+      coin <- map fst . take 60000 . drop 1000 <$> mh1 coinModel+      posteriorFraction "mh1 coin posterior" coin >>= assertBool "mh1 samples the coin posterior"+  , testCase "discrete uniform moves" $ do+      counts <- forM [17, 23, 29] $ \seed -> do+        setStdGen (mkStdGen seed)+        draws <- map fst . take 400 . drop 10 <$> mh1 discreteModel+        evaluate (rnf draws)+        pure (length (nub draws))+      assertBool ("mh1 moves a uniformdiscrete 10 latent; distinct values in 400 draws per seed: " ++ show counts)+        (all (> 1) counts)+  ]++-- Its only latent variable is uniformdiscrete 10; every outcome has weight 1.+discreteModel :: Meas Int+discreteModel = sample (uniformdiscrete 10)++data TreeRecord = TreeRecord { selectedTree :: Tree, recordSeed :: Int }++{-# NOINLINE treeRecord #-}+treeRecord :: Int -> TreeRecord+treeRecord seed = TreeRecord (randomTree (mkStdGen seed)) seed  -- A generator that returns one word forever. newtype ConstWord = ConstWord Word64
+ test/CompletedHooks.hs view
@@ -0,0 +1,1000 @@+{-# LANGUAGE ScopedTypeVariables #-}+{-# OPTIONS_GHC -fno-cse -fno-full-laziness -fno-float-in #-}+-- Avoid the test-module miscompilation matching GHC issue 27886.++-- The rational fixture is specified independently of this kernel. These+-- checks exercise both the finite acceptance rule and real heap-discovered+-- transitions, including the returned snapshot and retry continuation.+module Main where++import Control.Exception (AsyncException (ThreadKilled), SomeException, evaluate, throwIO, try)+import Control.DeepSeq (NFData (..), force)+import Control.Monad (foldM, forM_, unless, when)+import Control.Monad.Trans.Writer (WriterT (..), runWriterT)+import Data.IORef+import Data.List (elemIndex)+import Data.Monoid (Product (..))+import qualified Data.Map.Strict as Map+import Numeric.Log (Log (Exp))+import Data.Ratio ((%))+import qualified Data.Set as Set+import qualified Data.Vector as Vector+import Data.Word (Word64)+import GuidedReference+import FreshRetry (freshRetry)+import LazyPPL (Meas (..), Prob (..), Tree (..), randomTree, runProb, sample, score, uniform)+import LazyPPL.Internal.Sampler (randomLabel)+import LazyPPL.SingleSite.Hooks+import qualified LazyPPL.SingleSite.Internal as Internal+import System.Mem.StableName (makeStableName)+import System.IO.Unsafe (unsafePerformIO)+import System.Random (RandomGen (..), StdGen, mkStdGen)+import Statistics.Test.ChiSquared (chi2test, testSignificance)+import Statistics.Types (pValue)++type Bits = (Bool, Bool)+type TestKernel = Kernel String Bits++check :: String -> Bool -> IO ()+check label condition = unless condition (fail label)++must :: Either String a -> IO a+must = either fail pure++stateIndex :: Bits -> Int+stateIndex (first, second) = (if first then 2 else 0) + (if second then 1 else 0)++weights :: [Double]+weights = [1,2,3,4]++model :: Meas Bits+model = do+  first <- sample uniform+  second <- sample uniform+  let value = (first < 0.5, second < 0.5)+  score (weights !! stateIndex value)+  pure value++guideA :: [Rational]+guideA = [1%4, 3%4, 1%2, 3%4]++guide :: [Rational] -> SiteSelector String Bits+guide probabilities snapshot = case snapshotSites snapshot of+  [first, second] -> do+    let probability = probabilities !! stateIndex (fst (snapshotResult snapshot))+    law <- must (mkSiteLaw [(first, probability), (second, 1 - probability)])+    pure (Complete law)+  sites -> fail ("expected two discovered sites, got " ++ show sites)++initial :: TestKernel -> Int -> IO (Chain StdGen Bits)+initial kernel seed = do+  dynamicSeed <- newIORef seed >>= readIORef+  result <- initialise kernel (mkStdGen dynamicSeed)+  case result of+    Initialised chain -> pure chain+    InitialFailed err -> fail (show err)+    InitialInterrupted err _ -> fail (show err)++step :: TestKernel -> Chain StdGen Bits+     -> IO (Chain StdGen Bits, TransitionRecord)+step kernel chain = do+  result <- transition kernel chain+  case result of+    Transitioned next record -> pure (next, record)+    TransitionFailed err _ -> fail (show err)+    TransitionInterrupted err _ _ -> fail (show err)+++entry :: [[a]] -> Int -> Int -> a+entry matrix first second = matrix !! first !! second++close :: Double -> Double -> Bool+close first second = abs (first - second) <= 2e-14++idealReference :: IO ()+idealReference = do+  let stationary = [1%10,1%5,3%10,2%5]+  mapM_ (\row -> check "reference row sums to one" (sum row == 1))+    (qLocal ++ pLocal ++ pRefresh ++ pMixed)+  mapM_ (\(i,j) -> do+    let q = entry qLocal i j+        reverse = entry qLocal j i+        actualLog = acceptanceLog (log (weights !! i)) (log (weights !! j)) q reverse+        actual = maybe 0 (exp . fromRational) actualLog+        expected = entry aLocal i j+    check "acceptance matches four-state rational reference"+      (close actual (fromRational expected))+    if q > 0 then do+      let alpha = fromRational expected :: Double+      if alpha > 0 then check "acceptance branch below alpha"+        (accepts (alpha / 2) actualLog) else pure ()+      if alpha < 1 then check "rejection branch above alpha"+        (not (accepts ((1 + alpha) / 2) actualLog)) else pure ()+    else pure ()+    let offDiagonal = entry qLocal i j * entry aLocal i j+        expectedP = if i /= j then offDiagonal+          else 1 - sum [entry qLocal i k * entry aLocal i k | k <- [0..3], k /= i]+    check "local transition includes rejection self mass" (expectedP == entry pLocal i j)+    check "refresh mixture matches independent reference"+      (7%8 * entry pLocal i j + 1%8 * entry pRefresh i j == entry pMixed i j)+    check "mixed stationary flow is symmetric"+      (stationary !! i * entry pMixed i j == stationary !! j * entry pMixed j i)+    ) [(i,j) | i <- [0..3], j <- [0..3]]+  check "zero reverse mass rejects" (acceptanceLog 0 1 1 0 == Nothing)+  check "legacy strict acceptance boundary is retained"+    (not (accepts 0.5 (acceptanceLog (log 2) 0 1 1)))+  check "both zero weights reject" (acceptanceLog (-1/0) (-1/0) 1 1 == Nothing)+  check "positive state escapes zero weight" (accepts 0.99 (acceptanceLog (-1/0) 0 1 1))+  check "large log difference does not overflow acceptance"+    (not (accepts 0.01 (acceptanceLog 1e308 (-1e308) 1 1)))+  check "stale-guide refutation has nonzero exact flow defect"+    ((23%640) - (9%640) == (7%320))+  putStrLn "PASS exact four-state Q, acceptance, P, refresh mixture and detailed flows"+  putStrLn "REFUTATION stale reverse guide: forward flow 23/640, reverse 9/640, defect 7/320"++candidateIndex :: TransitionRecord -> IO Int+candidateIndex record = case candidateLogWeight record of+  Nothing -> fail "missing candidate weight"+  Just value -> case [index | (index, weight) <- zip [0..] weights, close value (log weight)] of+    [index] -> pure index+    _ -> fail ("candidate weight does not identify reference state: " ++ show value)++sameSnapshot :: Chain StdGen a -> Chain StdGen a -> IO Bool+sameSnapshot first second = do+  left <- evaluate (chainSnapshot first) >>= makeStableName+  right <- evaluate (chainSnapshot second) >>= makeStableName+  pure (left == right)++actualTransitions :: IO ()+actualTransitions = do+  kernel <- must (mkKernel (1%8) (pureEvaluator model) (guide guideA))+  start <- initial kernel 8801+  (_, seen, witnessed) <- foldM (one kernel) (start, Set.empty, False) [1..1600 :: Int]+  check "real transitions include accepted, rejected and full-refresh moves"+    (all (\tag -> Set.member tag seen) ["accepted", "rejected", "refresh"])+  check "actual state-dependent reverse-guide witness was encountered" witnessed+  putStrLn ("PASS real completed transitions: " ++ show (Set.toAscList seen))+  where+    one kernel (current, seen, witnessed) _ = do+      (next, record) <- step kernel current+      let i = stateIndex (fst (snapshotResult (chainSnapshot current)))+      j <- candidateIndex record+      label <- maybe (fail "missing acceptance label") pure (acceptanceUniform record)+      let alpha = case proposalKind record of+            RefreshAll -> min 1 (weights !! j / weights !! i)+            ResampleSite _ -> fromRational (entry aLocal i j)+            NoActiveSite -> error "reference model has two sites"+          expected = label < alpha+          actual = decision record == Accepted+          nextIndex = stateIndex (fst (snapshotResult (chainSnapshot next)))+      check "actual decision matches independent reference" (actual == expected)+      check "accepted state or retained state is returned" (nextIndex == if actual then j else i)+      check "completed proposal advances exactly one transition"+        (chainTransitions next == chainTransitions current + 1)+      case proposalKind record of+        ResampleSite selected -> do+          position <- maybe (fail "selected site is not active") pure+            (elemIndex selected (snapshotSites (chainSnapshot current)))+          let probabilities = if position == 0 then guideA else map (1-) guideA+          check "forward guide is assessed at current state"+            (forwardSiteMass record == Just (probabilities !! i))+          check "reverse guide is recomputed at candidate state"+            (reverseSiteMass record == Just (probabilities !! j))+        _ -> pure ()+      if actual then pure () else do+        retained <- sameSnapshot current next+        check "rejection retains actual accepted Snapshot object" retained+      let asym = i == 0 && j == 1 && case proposalKind record of+            ResampleSite _ -> True+            _ -> False+      if asym && not witnessed then putStrLn ("ACTUAL reverse-guide witness: " ++ show record) else pure ()+      let tags = (if actual then "accepted" else "rejected") :+            ["refresh" | proposalKind record == RefreshAll]+      pure (next, foldr Set.insert seen tags, witnessed || asym)++transitionMatrix :: IO ()+transitionMatrix = do+  matrixFixture guideA pLocal [(i,j) | i <- [0..3], j <- [0..3], i /= j,+                                      entry qLocal i j > 0]+  matrixFixture [1%4,3%4,0,3%4] pMissing+    [(0,1),(0,2),(1,0),(1,3),(2,3),(3,1),(3,2)]++matrixFixture :: [Rational] -> [[Rational]] -> [(Int, Int)] -> IO ()+matrixFixture probabilities reference pairs = do+  -- These probabilities are assessed from transition records and an assumed+  -- fair redraw; the frequency tests separately count observed transitions.+  kernel <- must (mkKernel 0 (pureEvaluator model) (guide probabilities))+  start <- initial kernel 8801+  (_, edges) <- foldM (one kernel) (start, Map.empty) [1..1600 :: Int]+  check "all one-coordinate transitions are observed" (all (`Map.member` edges) pairs)+  let off i j = Map.findWithDefault 0 (i,j) edges+      matrix = [[if i == j then 1 - sum [off i k | k <- [0..3], k /= i]+                           else off i j | j <- [0..3]] | i <- [0..3]]+      multiply distribution = [sum [distribution !! i * matrix !! i !! j | i <- [0..3]]+                              | j <- [0..3]]+      stationary = iterate multiply [1,0,0,0] !! 1000+  mapM_ (\(i,j) -> check ("assessed transition probability " ++ show (i,j))+            (close (matrix !! i !! j) (fromRational (entry reference i j))))+        [(i,j) | i <- [0..3], j <- [0..3]]+  mapM_ (\(actual, expected) -> check "stationary distribution"+            (close actual (fromRational expected)))+        (zip stationary [1%10,1%5,3%10,2%5])+  putStrLn ("PASS assessed transition probabilities and stationary distribution: " ++ show matrix ++ " " ++ show stationary)+  where+    one kernel (current, edges) _ = do+      (next, record) <- step kernel current+      let i = stateIndex (fst (snapshotResult (chainSnapshot current)))+      j <- candidateIndex record+      let probability = do+            mass <- forwardSiteMass record+            let acceptance = maybe 0 (exp . fromRational) (logAcceptance record)+            pure (fromRational mass / 2 * acceptance)+      pure (next, if i /= j then maybe edges (\p -> Map.insert (i,j) p edges) probability else edges)++evaluatedReplacementVisible :: IO ()+evaluatedReplacementVisible = do+  seed <- newIORef (2011 :: Int) >>= readIORef+  fresh <- evaluate (randomTree (mkStdGen seed))+  freshSites <- Internal.trunc fresh >>= evaluate . force . Internal.getSites+  replacement <- evaluate $ case randomTree (mkStdGen (seed + 1)) of Tree value _ -> value+  historical <- evaluate (Internal.mutateNodes (randomTree (mkStdGen seed)) (Map.singleton [] replacement))+  historicalSites <- Internal.trunc historical >>= evaluate . force . Internal.getSites+  check "fresh undemanded tree has no sites" (null freshSites)+  check "evaluated replacement fails fresh site discovery" (not (null historicalSites))+  putStrLn ("PASS evaluated replacement appears in site discovery: " ++ show historicalSites)++zeroWeightTransitions :: IO ()+zeroWeightTransitions = do+  let zeroModel = do+        first <- sample uniform+        second <- sample uniform+        let value = (first < 0.5, second < 0.5)+        score (if value == (False, False) then 0 else 1)+        pure value+      isZero weight = isInfinite weight && weight < 0+  kernel <- must (mkKernel 0 (pureEvaluator zeroModel) (guide guideA))+  outcomes <- mapM (\seed -> do+    current <- initial kernel seed+    (_, record) <- step kernel current+    newWeight <- maybe (fail "missing candidate weight") pure (candidateLogWeight record)+    let oldZero = isZero (previousLogWeight record)+        newZero = isZero newWeight+        expected = if oldZero && newZero then Just Rejected+                   else if oldZero then Just Accepted+                   else if newZero then Just Rejected+                   else Nothing+    case expected of+      Just verdict -> check "zero-weight transition decision" (decision record == verdict)+      Nothing -> pure ()+    pure (oldZero,newZero)) [1..400]+  mapM_ (\pair -> check ("zero-weight case " ++ show pair) (pair `elem` outcomes))+    [(True,True),(True,False),(False,True)]+  putStrLn "PASS zero and current-zero transitions"++changingSiteMatrix :: IO ()+changingSiteMatrix = do+  let variable = do+        branch <- sample uniform+        if branch < 0.5 then do+          value <- sample uniform+          let first = value < 0.5+          score (if first then 2 else 4)+          pure (True, Just first)+        else score 1 >> pure (False, Nothing)+      readBits = do+        branch <- sample uniform+        value <- sample uniform+        pure (branch < 0.5, value < 0.5)+      latent chain =+        let (seed, _, substitutions) = chainSources chain+            source = Internal.mutateNodes (randomTree seed) (Map.fromList substitutions)+            Meas action = readBits+            (bits, _) = runProb (runWriterT action) source+        in case bits of+          (False, False) -> 0+          (False, True) -> 1+          (True, True) -> 2+          (True, False) -> 3+      referenceStationary = [1%8,1%8,1%4,1%2]+  mapM_ (\row -> check "changing-site reference row sums to one" (sum row == 1)) pChanging+  mapM_ (\(i,j) -> check "changing-site reference has symmetric flows"+    (referenceStationary !! i * entry pChanging i j ==+     referenceStationary !! j * entry pChanging j i)) [(i,j) | i <- [0..3], j <- [0..3]]+  kernel <- must (mkKernel 0 (pureEvaluator variable) uniformSites)+    :: IO (Kernel String (Bool, Maybe Bool))+  begun <- initialise kernel (mkStdGen 8808)+  start <- case begun of+    Initialised chain -> pure chain+    InitialFailed err -> fail (show err)+    InitialInterrupted err _ -> fail (show err)+  rows <- newIORef Map.empty+  currentRef <- newIORef start+  forM_ [1..100000 :: Int] $ \_ -> do+    current <- readIORef currentRef+    let i = latent current+    outcome <- transition kernel current+    next <- case outcome of+      Transitioned chain _ -> pure chain+      TransitionFailed err _ -> fail (show err)+      TransitionInterrupted err _ _ -> fail (show err)+    let j = latent next+        visible = fst (snapshotResult (chainSnapshot current))+        expectedVisible = case i of+          0 -> (False, Nothing)+          1 -> (False, Nothing)+          2 -> (True, Just True)+          _ -> (True, Just False)+    check "reconstructed latent state agrees with the visible result" (visible == expectedVisible)+    modifyIORef' rows (Map.insertWith (+) (i,j) (1 :: Int))+    writeIORef currentRef next+  counts <- readIORef rows+  forM_ [0..3] $ \i -> do+    let observed = [Map.findWithDefault 0 (i,j) counts | j <- [0..3]]+        expected = pChanging !! i+        total = fromIntegral (sum observed)+        nonzero = [(n, total * fromRational p) | (n,p) <- zip observed expected, p > 0]+    check "impossible changing-site transitions are absent"+      (and [n == 0 | (n,p) <- zip observed expected, p == 0])+    result <- maybe (fail "changing-site frequency test needs two bins") pure+      (chi2test 0 (Vector.fromList nonzero))+    let p = pValue (testSignificance result)+    putStrLn ("changing-site latent row " ++ show i ++ " counts=" ++ show observed ++ " p=" ++ show p)+    check "changing-site frequencies match the full-state reference" (p > 0.001)++interruption :: IO ()+interruption = do+  healthy <- must (mkKernel 0 (pureEvaluator model) (guide guideA))+  current <- initial healthy 8802+  (expected, expectedRecord) <- step healthy current+  entered <- newIORef False+  resumedSameTree <- newIORef False+  let faulty fresh = do+        tree <- fresh+        originalName <- makeStableName tree+        writeIORef entered True+        pure (Suspend "candidate interrupted" (do+          resumedName <- makeStableName tree+          writeIORef resumedSameTree (resumedName == originalName)+          pureEvaluator model (pure tree)))+  faultKernel <- must (mkKernel 0 faulty (guide guideA))+  result <- transition faultKernel current+  case result of+    Transitioned _ _ -> fail "interruption was converted to a completed transition"+    TransitionFailed err _ -> fail (show err)+    TransitionInterrupted err retained pending -> do+      check "typed interruption is preserved" (err == CallbackInterrupted "candidate interrupted")+      same <- sameSnapshot current retained+      check "interruption retains actual accepted Snapshot" same+      check "interruption keeps source and transition count"+        (chainSources current == chainSources retained &&+         chainTransitions current == chainTransitions retained)+      resumed <- resumeTransition pending+      case resumed of+        TransitionFailed second _ -> fail (show second)+        TransitionInterrupted second _ _ -> fail (show second)+        Transitioned next record -> do+          check "explicit retry uses original candidate source" =<< readIORef resumedSameTree+          check "explicit retry matches uninterrupted transition"+            (chainSources next == chainSources expected &&+             snapshotResult (chainSnapshot next) == snapshotResult (chainSnapshot expected) &&+             record == expectedRecord)+  check "fault callback executed" =<< readIORef entered+  putStrLn "PASS typed candidate interruption, identical pending Tree, exact retry and snapshot retention"++reverseGuideInterruption :: IO ()+reverseGuideInterruption = do+  calls <- newIORef (0 :: Int)+  let ordinary = guide guideA+      faulty snapshot = do+        count <- atomicModifyIORef' calls (\n -> (n+1,n+1))+        if count == 2+          then pure (Suspend (CallbackInterrupted "reverse guide interrupted") (ordinary snapshot))+          else ordinary snapshot+  good <- must (mkKernel 0 (pureEvaluator model) ordinary)+  bad <- must (mkKernel 0 (pureEvaluator model) faulty)+  current <- initial good 8803+  (expected, expectedRecord) <- step good current+  result <- transition bad current+  case result of+    Transitioned _ _ -> fail "reverse-guide failure silently completed"+    TransitionFailed err _ -> fail (show err)+    TransitionInterrupted err retained pending -> do+      check "reverse-guide interruption is typed" (err == CallbackInterrupted "reverse guide interrupted")+      check "reverse-guide failure did not advance source" (chainSources retained == chainSources current)+      same <- sameSnapshot retained current+      check "reverse-guide failure retained accepted object" same+      resumed <- resumeTransition pending+      case resumed of+        TransitionFailed second _ -> fail (show second)+        TransitionInterrupted second _ _ -> fail (show second)+        Transitioned next record -> check "reverse-guide retry preserves exact proposal"+          (record == expectedRecord && chainSources next == chainSources expected &&+           snapshotResult (chainSnapshot next) == snapshotResult (chainSnapshot expected))+      count <- readIORef calls+      check "retry did not rerun the forward selector or draw another proposal" (count == 2)+  putStrLn "PASS candidate-state guide interruption and same-proposal retry"++missingReverseAndRefresh :: IO ()+missingReverseAndRefresh = do+  kernel <- must (mkKernel (1%8) (pureEvaluator model) (guide [1%4,3%4,0,3%4]))+  start <- initial kernel 8804+  (_, found) <- foldM (one kernel) (start, False) [1..1200 :: Int]+  check "a real zero-reverse-support proposal was refuted" found+  locked <- must (mkKernel 0 (pureEvaluator model) (guide (replicate 4 1)))+  refreshing <- must (mkKernel (1%8) (pureEvaluator model) (guide (replicate 4 1)))+  lockedStart <- initial locked 8805+  let initialSecond = snd (fst (snapshotResult (chainSnapshot lockedStart)))+  localEnd <- foldM (\current _ -> fst <$> step locked current) lockedStart [1..100 :: Int]+  check "local guide never selects the second coordinate"+    (snd (fst (snapshotResult (chainSnapshot localEnd))) == initialSecond)+  (_, moved) <- foldM (\(current, seen) _ -> do+       (next, record) <- step refreshing current+       let second = snd (fst (snapshotResult (chainSnapshot next)))+       pure (next, seen || (proposalKind record == RefreshAll && second /= initialSecond)))+    (lockedStart, False) [1..300 :: Int]+  check "full refresh can move a coordinate excluded by the site guide" moved+  putStrLn "PASS real missing-reverse rejection and full-refresh movement outside local guide support"+  where+    one kernel (current, found) _ = do+      (next, record) <- step kernel current+      let zeroReverse = reverseSiteMass record == Just 0+      if zeroReverse then do+        check "zero reverse-support move is rejected" (decision record == Rejected)+        same <- sameSnapshot current next+        check "zero reverse-support preserves actual snapshot" same+      else pure ()+      pure (next, found || zeroReverse)++noSitesAndUsedSiteCount :: IO ()+noSitesAndUsedSiteCount = do+  fixed <- must (mkKernel 0 (pureEvaluator (score 2 >> pure (7 :: Int))) uniformSites)+    :: IO (Kernel String Int)+  begun <- initialise fixed (mkStdGen 8807)+  start <- case begun of+    Initialised chain -> pure chain+    InitialFailed err -> fail (show err)+    InitialInterrupted err _ -> fail (show err)+  check "constant model has no active sites" (null (snapshotSites (chainSnapshot start)))+  empty <- uniformSites (chainSnapshot start) :: IO (Completion (KernelError String) SiteLaw)+  case empty of+    Failed (InvalidSiteLaw _) -> pure ()+    _ -> fail "empty uniform site law must fail with InvalidSiteLaw"+  one <- transition fixed start+  case one of+    TransitionFailed err _ -> fail (show err)+    TransitionInterrupted err _ _ -> fail (show err)+    Transitioned next record -> do+      unchanged <- sameSnapshot start next+      check "no-site transition retains the exact snapshot" unchanged+      check "no-site transition is the identity rather than a proposal"+        (proposalKind record == NoActiveSite && decision record == Stayed &&+         snapshotResult (chainSnapshot next) == snapshotResult (chainSnapshot start))++  varying <- must (mkKernel 0 (pureEvaluator variableModel) uniformSites)+    :: IO (Kernel String (Bool, Maybe Double))+  initialValue <- initialise varying (mkStdGen 8808)+  first <- case initialValue of+    Initialised chain -> pure chain+    InitialFailed err -> fail (show err)+    InitialInterrupted err _ -> fail (show err)+  (_, witnessed) <- foldM (countStep varying) (first, False) [1..400 :: Int]+  check "a changing used-site-count transition was exercised" witnessed+  putStrLn "PASS no-site identity and actual old/new used-site-count correction"+  where+    variableModel = do+      branch <- sample uniform+      if branch < 0.5 then do+        second <- sample uniform+        score 3+        pure (True, Just second)+      else pure (False, Nothing)+    countStep kernel (current, witnessed) _ = do+      outcome <- transition kernel current+      case outcome of+        TransitionFailed err _ -> fail (show err)+        TransitionInterrupted err _ _ -> fail (show err)+        Transitioned next record -> do+          let oldCount = length (snapshotSites (chainSnapshot current))+          newWeight <- maybe (fail "missing varying-count candidate weight") pure (candidateLogWeight record)+          let newCount = if close newWeight (log 3) then 2 else 1 :: Int+              oldTarget = if oldCount == 2 then 3 else 1 :: Double+              newTarget = if newCount == 2 then 3 else 1 :: Double+              alpha = min 1 (newTarget / oldTarget * fromIntegral oldCount / fromIntegral newCount)+          check "uniform selection uses the current active-site count"+            (forwardSiteMass record == Just (1 / fromIntegral oldCount))+          check "uniform reverse selection uses the candidate active-site count"+            (reverseSiteMass record == Just (1 / fromIntegral newCount))+          label <- maybe (fail "missing varying-count acceptance label") pure (acceptanceUniform record)+          check "actual transition includes the used-site-count factor"+            ((decision record == Accepted) == (label < alpha))+          let witness = oldCount == 2 && newCount == 1+          if witness && not witnessed+            then putStrLn ("ACTUAL used-site-count witness: " ++ show record) else pure ()+          pure (next, witnessed || witness)++cancellation :: IO ()+cancellation = do+  kernel <- must (mkKernel 0 (\_ -> throwIO ThreadKilled) (guide guideA))+  result <- try (initialise kernel (mkStdGen 8806))+    :: IO (Either AsyncException (InitialResult String StdGen Bits))+  check "asynchronous cancellation propagates" (case result of Left ThreadKilled -> True; _ -> False)+  putStrLn "PASS asynchronous cancellation is not a rejection or zero weight"+++-- Reuse the pre-existing defensive witness against the new transition path.+-- Its deliberately stateful NFData is outside the stable-program contract:+-- this checks reverse-site rejection, not soundness for hidden mutable values.+data DemandObservation = DemandObservation Double Tree (IORef Bool)++instance NFData DemandObservation where+  rnf (DemandObservation value (Tree root _) first) = unsafePerformIO $ do+    _ <- evaluate (rnf value)+    initialDemand <- atomicModifyIORef' first (\old -> (False, old))+    if initialDemand then evaluate root >> pure () else pure ()++observeDemand :: IORef Bool -> Tree -> DemandObservation+observeDemand first tree@(Tree _ (Tree value _ : _)) =+  DemandObservation value tree first+observeDemand _ _ = error "test source has no first child"+{-# NOINLINE observeDemand #-}++observedValue :: DemandObservation -> Double+observedValue (DemandObservation value _ _) = value++reverseSiteDiscovery :: IO ()+reverseSiteDiscovery = do+  totals <- mapM oneSeed [1..16]+  check "unused-root proposals were never accepted" (all (\(bad,_,_) -> bad == 0) totals)+  check "the disappearing-site guard was actually exercised" (sum [missing | (_,_,missing) <- totals] > 0)+  check "the guard is not an always-reject kernel" (all (\(_,moved,_) -> moved > 0) totals)+  putStrLn ("PASS inherited disappearing-site control: " ++ show totals)+  where+    oneSeed seed = do+      first <- newIORef True+      let evaluateTree = pureEvaluator (sample (Prob (observeDemand first)))+            :: Evaluator String DemandObservation+      kernel <- must (mkKernel 0 evaluateTree uniformSites)+      dynamicSeed <- newIORef seed >>= readIORef+      begun <- initialise kernel (mkStdGen dynamicSeed)+      start <- case begun of+        Initialised chain -> pure chain+        InitialFailed err -> fail (show err)+        InitialInterrupted err _ -> fail (show err)+      (_, bad, moved, missing) <- foldM (oneStep kernel) (start,0,0,0) [1..64 :: Int]+      pure (bad,moved,missing)+    oneStep kernel (current,bad,moved,missing) _ = do+      result <- transition kernel current+      case result of+        TransitionFailed err _ -> fail (show err)+        TransitionInterrupted err _ _ -> fail (show err)+        Transitioned next record -> do+          let oldValue = observedValue (fst (snapshotResult (chainSnapshot current)))+              newValue = observedValue (fst (snapshotResult (chainSnapshot next)))+              unsupportedAccepted = oldValue == newValue && decision record == Accepted+              absent = reverseSiteMass record == Just 0+          if absent then do+            check "a vanished reverse site rejects" (decision record == Rejected)+            same <- sameSnapshot current next+            check "vanished reverse site retains actual snapshot" same+          else pure ()+          pure (next, bad + fromEnum unsupportedAccepted,+                moved + fromEnum (oldValue /= newValue), missing + fromEnum absent)+++permanentWeight :: IO ()+permanentWeight = do+  let invalidEvaluator fresh = do+        tree <- fresh+        pure (Complete (tree, ((False, False), Product (Exp (0/0)))))+  kernel <- must (mkKernel 0 invalidEvaluator (guide guideA))+  result <- initialise kernel (mkStdGen 1901)+  case result of+    Initialised _ -> fail "NaN completed weight was accepted"+    InitialFailed (InvalidCompletedWeight weight) ->+      check "invalid weight remains NaN" (isNaN weight)+    InitialInterrupted err _ -> fail ("invalid weight offered retry: " ++ show err)+    InitialFailed err -> fail ("unexpected error: " ++ show err)+  putStrLn "PASS invalid completed weight is terminal"++permanentSelections :: IO ()+permanentSelections = do+  healthy <- must (mkKernel 0 (pureEvaluator model) (guide guideA))+  start <- initial healthy 1902+  let outside _ = do+        law <- must (mkSiteLaw [([999], 1)])+        pure (Complete law)+      zero snapshot = case snapshotSites snapshot of+        [first, second] -> do+          law <- must (mkSiteLawUnchecked (\g -> (second, g)) [(first, 1), (second, 0)])+          pure (Complete law)+        sites -> fail ("expected two active sites, got " ++ show sites)+  outsideKernel <- must (mkKernel 0 (pureEvaluator model) outside)+  outsideResult <- transition outsideKernel start+  case outsideResult of+    TransitionFailed (InvalidSiteLaw _) retained ->+      check "invalid law retains source" (chainSources retained == chainSources start)+    _ -> fail "expected a permanent invalid site law"+  zeroKernel <- must (mkKernel 0 (pureEvaluator model) zero)+  zeroResult <- transition zeroKernel start+  case zeroResult of+    TransitionFailed (InvalidSelection _) retained ->+      check "invalid selection retains source" (chainSources retained == chainSources start)+    _ -> fail "expected a permanent zero-mass selection"+  putStrLn "PASS invalid site law and zero-mass selection are terminal"++checkedSiteLaw :: IO ()+checkedSiteLaw = do+  let selector snapshot = case snapshotSites snapshot of+        [first, second] -> do+          law <- must (mkSiteLaw [(first, 1), (second, 0)])+          pure (Complete law)+        sites -> fail ("expected two sites, got " ++ show sites)+  kernel <- must (mkKernel 0 (pureEvaluator model) selector)+  start <- initial kernel 1904+  _ <- foldM (\current _ -> do+    let first = head (snapshotSites (chainSnapshot current))+    (next, record) <- step kernel current+    check "checked law never draws zero-mass site" (proposalKind record == ResampleSite first)+    pure next) start [1..80 :: Int]+  check "checked law rejects invalid mass" (case mkSiteLaw [([], 2)] of Left _ -> True; Right _ -> False)+  putStrLn "PASS checked site law derives its draw from its finite masses"++synchronousFailure :: IO ()+synchronousFailure = do+  count <- newIORef (0 :: Int)+  let flaky fresh = do+        n <- atomicModifyIORef' count (\x -> (x+1,x+1))+        if n == 1 then fail "temporary synchronous failure" else pureEvaluator model fresh+  kernel <- must (mkKernel 0 flaky (guide guideA))+  result <- initialise kernel (mkStdGen 1903)+  case result of+    InitialInterrupted (SynchronousFailure _) pending -> do+      resumed <- resumeInitial pending+      case resumed of+        Initialised _ -> pure ()+        InitialFailed err -> fail ("retry failed permanently: " ++ show err)+        InitialInterrupted err _ -> fail ("retry failed: " ++ show err)+    _ -> fail "synchronous failure was not typed as retryable"+  check "synchronous retry invokes the evaluator again" . (== 2) =<< readIORef count+  putStrLn "PASS synchronous failure is retryable"++permanentCallbackFailure :: IO ()+permanentCallbackFailure = do+  let broken _ = pure (Failed "permanent callback")+  kernel <- must (mkKernel 0 broken (guide guideA)) :: IO TestKernel+  result <- initialise kernel (mkStdGen 1910)+  case result of+    InitialFailed (CallbackFailed "permanent callback") -> pure ()+    _ -> fail "permanent callback did not fail"++deterministicSelectorThrow :: IO ()+deterministicSelectorThrow = do+  attempts <- newIORef (0 :: Int)+  let broken _ = modifyIORef' attempts (+ 1) >> fail "deterministic selector failure"+  kernel <- must (mkKernel 0 (pureEvaluator model) broken) :: IO TestKernel+  start <- initial kernel 1911+  result <- transition kernel start+  case result of+    TransitionInterrupted (SynchronousFailure _) _ pending -> do+      check "selector is attempted once before an explicit resume" . (== 1) =<< readIORef attempts+      resumed <- resumeTransition pending+      case resumed of+        TransitionInterrupted (SynchronousFailure _) _ _ -> pure ()+        _ -> fail "deterministic selector throw did not suspend on explicit retry"+      check "each explicit resume attempts selector only once" . (== 2) =<< readIORef attempts+    _ -> fail "selector throw did not suspend"++deferredSelectorThrow :: IO ()+deferredSelectorThrow = do+  good <- must (mkKernel 0 (pureEvaluator model) (guide guideA))+  start <- initial good 1912+  let broken _ = pure (Complete (error "deferred selector failure"))+  bad <- must (mkKernel 0 (pureEvaluator model) broken)+  result <- try (transition bad start) :: IO (Either SomeException (TransitionResult String StdGen Bits))+  case result of+    Right (TransitionInterrupted (SynchronousFailure _) retained _) ->+      check "deferred selector failure retains source" (chainSources retained == chainSources start)+    Left _ -> fail "deferred selector failure escaped instead of suspending"+    _ -> fail "deferred selector failure did not suspend"++data DrawGen = Start Bool | ChainSource Bool | LocalSource Bool+  | LabelSource Bool | BadAcceptance | Good deriving (Eq, Show)++instance RandomGen DrawGen where+  split (Start badFirst) = (Good, ChainSource badFirst)+  split (ChainSource badFirst) = (LocalSource badFirst, Good)+  split (LocalSource badFirst) = (Good, LabelSource badFirst)+  split _ = (Good, Good)+  genWord64 (LabelSource True) = error "replacement draw"+  genWord64 (LabelSource False) = (0, BadAcceptance)+  genWord64 BadAcceptance = error "acceptance draw"+  genWord64 g = (0, g)++actualDrawFailures :: IO ()+actualDrawFailures = forM_ [True, False] $ \badFirst -> do+  let root = Meas (WriterT (Prob (\(Tree x _) -> (x, Product 1))))+  kernel <- must (mkKernel 0 (pureEvaluator root) uniformSites) :: IO (Kernel String Double)+  begun <- initialise kernel (Start badFirst)+  start <- case begun of+    Initialised chain -> pure chain+    _ -> fail "root model did not initialise"+  result <- try (do+    outcome <- transition kernel start+    case outcome of+      Transitioned next record -> do+        _ <- evaluate (decision record)+        _ <- evaluate (force (fst (snapshotResult (chainSnapshot next))))+        _ <- evaluate (chainTransitions next)+        pure outcome+      _ -> pure outcome) :: IO (Either SomeException (TransitionResult String DrawGen Double))+  case result of+    Right (TransitionInterrupted (SynchronousFailure _) retained _) -> do+      check "draw failure retains sources" (chainSources retained == chainSources start)+      check "draw failure retains transition count" (chainTransitions retained == chainTransitions start)+      check "draw failure retains value" (fst (snapshotResult (chainSnapshot retained)) == fst (snapshotResult (chainSnapshot start)))+    Left _ -> fail ("actual label draw escaped: " ++ show badFirst)+    _ -> fail ("actual label draw did not suspend: " ++ show badFirst)++discardedDrawSource :: IO ()+discardedDrawSource = do+  let root = Meas (WriterT (Prob (\(Tree x _) -> (x, Product 1))))+      select snapshot = case snapshotSites snapshot of+        [site] -> do+          law <- must (mkSiteLawUnchecked (\_ -> (site, error "discarded source")) [(site, 1)])+          pure (Complete law)+        _ -> fail "expected one site"+  kernel <- must (mkKernel 0 (pureEvaluator root) select) :: IO (Kernel String Double)+  begun <- initialise kernel (mkStdGen 1913)+  case begun of+    Initialised start -> do+      result <- transition kernel start+      case result of+        Transitioned chain record -> do+          check "discarded source does not affect decision" (decision record == Accepted)+          check "discarded source does not prevent advancement" (chainTransitions chain == 1)+          _ <- evaluate (fst (snapshotResult (chainSnapshot chain)))+          pure ()+        _ -> fail "discarded source interrupted transition"+    _ -> fail "root model did not initialise"++data RefreshGen = RefreshStart | RefreshChain | RefreshLocal | RefreshLabel+  | RefreshGood deriving (Eq, Show)++instance RandomGen RefreshGen where+  split RefreshStart = (RefreshGood, RefreshChain)+  split RefreshChain = (RefreshLocal, RefreshGood)+  split RefreshLocal = (RefreshGood, RefreshLabel)+  split _ = (RefreshGood, RefreshGood)+  genWord64 RefreshLabel = error "refresh acceptance draw"+  genWord64 g = (0, g)++refreshDrawFailure :: IO ()+refreshDrawFailure = do+  let root = Meas (WriterT (Prob (\(Tree x _) -> (x, Product 1))))+  kernel <- must (mkKernel 1 (pureEvaluator root) uniformSites) :: IO (Kernel String Double)+  begun <- initialise kernel RefreshStart+  start <- case begun of+    Initialised chain -> pure chain+    _ -> fail "refresh model did not initialise"+  result <- try (do+    outcome <- transition kernel start+    case outcome of+      Transitioned chain record -> do+        _ <- evaluate (decision record)+        _ <- evaluate (fst (snapshotResult (chainSnapshot chain)))+        pure outcome+      _ -> pure outcome) :: IO (Either SomeException (TransitionResult String RefreshGen Double))+  case result of+    Right (TransitionInterrupted (SynchronousFailure _) retained _) -> do+      check "refresh draw failure retains sources" (chainSources retained == chainSources start)+      check "refresh draw failure retains transition count" (chainTransitions retained == 0)+    Left _ -> fail "refresh acceptance draw escaped"+    _ -> fail "refresh acceptance draw did not suspend"++deferredDrawSiteThrow :: IO ()+deferredDrawSiteThrow = do+  good <- must (mkKernel 0 (pureEvaluator model) (guide guideA))+  start <- initial good 1914+  let broken snapshot = case snapshotSites snapshot of+        first:_ -> do+          law <- must (mkSiteLawUnchecked (\g -> (first ++ error "deferred site tail", g)) [(first, 1)])+          pure (Complete law)+        [] -> fail "expected active sites"+  bad <- must (mkKernel 0 (pureEvaluator model) broken)+  result <- try (transition bad start) :: IO (Either SomeException (TransitionResult String StdGen Bits))+  case result of+    Right (TransitionInterrupted (SynchronousFailure _) retained _) ->+      check "draw failure retains source" (chainSources retained == chainSources start)+    Left _ -> fail "deferred draw site escaped instead of suspending"+    _ -> fail "deferred draw site did not suspend"++independentSiteDraw :: IO ()+independentSiteDraw = do+  let fairModel = do+        first <- sample uniform+        second <- sample uniform+        pure (first < 0.5, second < 0.5)+      selected snapshot = case snapshotSites snapshot of+        [first, second] -> do+          law <- must (mkSiteLawUnchecked+            (\g -> let (u, _) = randomLabel g+                    in (if u < 0.5 then first else second, g))+            [(first, 1%2), (second, 1%2)])+          pure (Complete law)+        _ -> fail "expected two sites"+  kernel <- must (mkKernel 0 (pureEvaluator fairModel) selected) :: IO TestKernel+  observations <- mapM (\seed -> do+    current <- initial kernel seed+    (next, record) <- step kernel current+    let sites = snapshotSites (chainSnapshot current)+        (first, second) = fst (snapshotResult (chainSnapshot next))+        index = case proposalKind record of+          ResampleSite site | site == sites !! 0 -> 0+                            | site == sites !! 1 -> 1+          _ -> error "expected selected site"+    pure (stateIndex (fst (snapshotResult (chainSnapshot current))), index,+          if index == 0 then first else second, stateIndex (first, second))) [1..8000]+  let balanced = concat [take 500 [x | x@(old, _, _, _) <- observations, old == i] | i <- [0..3]]+      fraction xs = fromIntegral (length (filter id xs)) / fromIntegral (length xs) :: Double+      conditional i = fraction [value | (_, site, value, _) <- balanced, site == i]+      endFraction i = fraction [end == i | (_, _, _, end) <- balanced]+  check "sample contains each initial state" (length balanced == 2000)+  putStrLn ("conditional replacement frequencies " ++ show (map conditional [0,1]) +++            "; successor frequencies " ++ show (map endFraction [0..3]))+  mapM_ (\i -> check "replacement remains fair conditional on selected site"+    (conditional i > 0.4 && conditional i < 0.6)) [0,1]+  mapM_ (\i -> check "one step preserves the uniform distribution"+    (endFraction i > 0.20 && endFraction i < 0.30)) [0..3]++deferredEvaluatorFailures :: IO ()+deferredEvaluatorFailures = do+  let completion _ = pure (error "deferred completion")+      payload _ = pure (Complete (error "deferred pair"))+      suspended _ = pure (Suspend "wait" (pure (Complete (error "deferred resumed pair"))))+      suspendedOuter _ = pure (Suspend "wait" (pure (error "resumed completion")))+      deep fresh = do+        tree <- fresh+        pure (Complete (tree, (error "deferred result", Product 1)))+      make evaluateTree = must (mkKernel 0 evaluateTree (guide guideA)) :: IO TestKernel+      classify result = case result of+        Left _ -> "escaped"+        Right (InitialInterrupted (SynchronousFailure _) _) -> "interrupted"+        Right (InitialFailed (InvalidCompletedResult _)) -> "failed"+        Right _ -> "other"+      run evaluator = do+        kernel <- make evaluator+        try (initialise kernel (mkStdGen 1915) >>= evaluate)+          :: IO (Either SomeException (InitialResult String StdGen Bits))+  first <- classify <$> run completion+  second <- classify <$> run payload+  pendingResult <- run suspended+  third <- case pendingResult of+    Right (InitialInterrupted (CallbackInterrupted "wait") pending) ->+      classify <$> (try (resumeInitial pending >>= evaluate)+        :: IO (Either SomeException (InitialResult String StdGen Bits)))+    _ -> pure "did not suspend"+  fourth <- classify <$> run deep+  outerPending <- run suspendedOuter+  fifth <- case outerPending of+    Right (InitialInterrupted (CallbackInterrupted "wait") pending) ->+      classify <$> (try (resumeInitial pending >>= evaluate)+        :: IO (Either SomeException (InitialResult String StdGen Bits)))+    _ -> pure "did not suspend"+  let observed = [first, second, third, fourth, fifth]+  putStrLn ("deferred evaluator results " ++ show observed)+  check "deferred evaluator failures are contained"+    (observed == ["interrupted", "interrupted", "interrupted", "failed", "interrupted"])++data ZeroGen = ZeroGen deriving Show++instance RandomGen ZeroGen where+  genWord64 _ = (0 :: Word64, ZeroGen)+  split _ = (ZeroGen, ZeroGen)++smallRefreshProbability :: IO ()+smallRefreshProbability = do+  kernel <- must (mkKernel (1 % (2 ^ (54 :: Int)))+    (pureEvaluator (pure ())) uniformSites) :: IO (Kernel String ())+  begun <- initialise kernel ZeroGen+  chain <- case begun of+    Initialised value -> pure value+    _ -> fail "initialisation failed"+  result <- transition kernel chain+  case result of+    Transitioned _ record -> check "positive refresh probability can select refresh"+      (proposalKind record == RefreshAll)+    _ -> fail "transition did not complete"++randomFrequencies :: IORef Bool -> IO ()+randomFrequencies completed = do+  -- The fixed seed, sample sizes and threshold are chosen before running.+  let seed = 57341+      burnIn = 1000 :: Int+      transitions = 100000 :: Int+      perRow = 5000 :: Int+      spacing = 64 :: Int+      alpha = 0.001 :: Double+      stationary = [1%10, 2%10, 3%10, 4%10]+  kernel <- must (mkKernel (1%8) (pureEvaluator model) (guide guideA))+  start <- initial kernel seed+  chainRef <- newIORef start+  rowsRef <- newIORef Map.empty+  visitsRef <- newIORef Map.empty+  spacedRef <- newIORef Map.empty+  totalsRef <- newIORef Map.empty+  forM_ [1 .. burnIn + transitions] $ \index -> do+    chain <- readIORef chainRef+    let from = stateIndex (fst (snapshotResult (chainSnapshot chain)))+    (next, _) <- step kernel chain+    writeIORef chainRef next+    let to = stateIndex (fst (snapshotResult (chainSnapshot next)))+    when (index > burnIn) $ do+      totals <- readIORef totalsRef+      when (Map.findWithDefault 0 from totals < perRow) $ do+        modifyIORef' rowsRef (Map.insertWith (+) (from,to) 1)+        modifyIORef' totalsRef (Map.insertWith (+) from 1)+      modifyIORef' visitsRef (Map.insertWith (+) to 1)+      when ((index - burnIn) `mod` spacing == 0) $+        modifyIORef' spacedRef (Map.insertWith (+) to 1)+  rows <- readIORef rowsRef+  visits <- readIORef visitsRef+  spaced <- readIORef spacedRef+  totals <- readIORef totalsRef+  check "each state has enough transitions" (all (\i -> Map.findWithDefault 0 i totals == perRow) [0..3])+  mapM_ (\i -> do+    let observed = [Map.findWithDefault 0 (i,j) rows | j <- [0..3]]+    p <- chiProbability observed (pMixed !! i)+    putStrLn ("frequency row " ++ show i ++ " counts=" ++ show observed ++ " p=" ++ show p)+    check "transition frequencies match the reference" (p > alpha)) [0..3]+  let observed = [Map.findWithDefault 0 i visits | i <- [0..3]]+  p <- chiProbability observed stationary+  let spacedCounts = [Map.findWithDefault 0 i spaced | i <- [0..3]]+  spacedP <- chiProbability spacedCounts stationary+  wrong <- chiProbability spacedCounts (replicate 4 (1%4))+  putStrLn ("stationary counts=" ++ show observed ++ " nominal-p=" ++ show p)+  putStrLn ("spaced stationary counts=" ++ show spacedCounts ++ " nominal-p=" ++ show spacedP ++ " wrong-uniform-p=" ++ show wrong)+  -- The chain states are dependent. The spaced comparison reduces dependence,+  -- so both stationary p-values are nominal rather than exact significance.+  check "spaced frequencies match the stationary distribution" (spacedP > alpha)+  check "wrong stationary distribution is detected" (wrong < alpha)+  writeIORef completed True+  where+    chiProbability counts probabilities = do+      let n = fromIntegral (sum counts)+          pairs = Vector.fromList (zip counts (map ((n *) . fromRational) probabilities))+      result <- maybe (fail "chi-squared test requires at least two bins") pure (chi2test 0 pairs)+      pure (pValue (testSignificance result))++main :: IO ()+main = do+  actualDrawFailures+  discardedDrawSource+  refreshDrawFailure+  freshRetry+  smallRefreshProbability+  deferredEvaluatorFailures+  independentSiteDraw+  frequencyCompleted <- newIORef False+  randomFrequencies frequencyCompleted+  check "frequency comparisons completed" =<< readIORef frequencyCompleted+  deferredDrawSiteThrow+  deferredSelectorThrow+  deterministicSelectorThrow+  permanentCallbackFailure+  permanentWeight+  permanentSelections+  synchronousFailure+  checkedSiteLaw+  idealReference+  actualTransitions+  transitionMatrix+  evaluatedReplacementVisible+  zeroWeightTransitions+  changingSiteMatrix+  interruption+  reverseGuideInterruption+  missingReverseAndRefresh+  noSitesAndUsedSiteCount+  reverseSiteDiscovery+  cancellation+
+ test/FreshRetry.hs view
@@ -0,0 +1,67 @@+{-# 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"
+ test/GuidedReference.hs view
@@ -0,0 +1,45 @@+-- | Independent ideal four-state reference, consumed by CompletedHooks.+--+-- States are 00, 01, 10, 11. Target weights are 1, 2, 3, 4. The probability+-- of choosing the first site is respectively 1/4, 3/4, 1/2, 3/4. A selected+-- coordinate is redrawn as a fair Boolean. A fixed 1/8 component redraws both.+--+-- For example, 00 -> 01 has local q=3/8, reverse q=1/8 and acceptance 2/3,+-- hence P=1/4. Its stationary flow is 1/40 in both directions. Reusing the+-- current guide in the reverse ratio instead gives mixed flows 23/640 and+-- 9/640, a defect of 7/320. Moving on rejection gives local flows 3/80 and+-- 1/40, a defect of 1/80. These literals were specified independently of the+-- kernel; they are not calculated by its acceptance or transition functions.+module GuidedReference (qLocal, aLocal, pLocal, pMissing, pChanging, pRefresh, pMixed) where++import Data.Ratio ((%))++qLocal, aLocal, pLocal, pMissing, pChanging, pRefresh, pMixed :: [[Rational]]+qLocal =+  [[1%2,3%8,1%8,0], [1%8,1%2,0,3%8],+   [1%4,0,1%2,1%4], [0,3%8,1%8,1%2]]+aLocal =+  [[1,2%3,1,0], [1,1,0,1],+   [1%6,0,1,2%3], [0,1%2,1,1]]+pLocal =+  [[5%8,1%4,1%8,0], [1%8,1%2,0,3%8],+   [1%24,0,19%24,1%6], [0,3%16,1%8,11%16]]+pMissing =+  [[3%4,1%4,0,0], [1%8,1%2,0,3%8],+   [0,0,5%6,1%6], [0,3%16,1%8,11%16]]+-- Inactive hidden false, inactive hidden true, active true, active false.+-- An inactive state activates with probability 1/2 and reveals its retained+-- bit. Active-to-inactive proposals have mass 1/4; their acceptances are 1+-- and 1/2 for weights 2 and 4. Switching the active bit has proposal mass+-- 1/4 and acceptances 1 and 1/2. The remaining mass stays in each state.+pChanging =+  [[1%2,0,0,1%2], [0,1%2,1%2,0],+   [0,1%4,1%2,1%4], [1%8,0,1%8,3%4]]+pRefresh =+  [[1%4,1%4,1%4,1%4], [1%8,3%8,1%4,1%4],+   [1%12,1%6,1%2,1%4], [1%16,1%8,3%16,5%8]]+pMixed =+  [[37%64,1%4,9%64,1%32], [1%8,31%64,1%32,23%64],+   [3%64,1%48,145%192,17%96], [1%128,23%128,17%128,87%128]]++
+ test/PlainOptimisedClient.hs view
@@ -0,0 +1,67 @@+module Main where++import Control.Monad (forM_, unless, when)+import Data.IORef (modifyIORef', newIORef, readIORef, writeIORef)+import qualified Data.Map.Strict as Map+import Data.Ratio ((%))+import qualified Data.Vector as Vector+import GuidedReference (pMixed)+import LazyPPL (Meas, sample, score, uniform)+import LazyPPL.SingleSite.Hooks+import Statistics.Test.ChiSquared (chi2test, testSignificance)+import Statistics.Types (pValue)+import System.Random (mkStdGen)++state :: (Bool, Bool) -> Int+state (a,b) = (if a then 2 else 0) + (if b then 1 else 0)++model :: Meas (Bool, Bool)+model = do+  a <- sample uniform+  b <- sample uniform+  let bits = (a < 0.5, b < 0.5)+  score ([1,2,3,4] !! state bits)+  pure bits++guide :: SiteSelector String (Bool, Bool)+guide snapshot = case snapshotSites snapshot of+  [a,b] -> do+    let p = [1%4,3%4,1%2,3%4] !! state (fst (snapshotResult snapshot))+    law <- either fail pure (mkSiteLaw [(a,p),(b,1-p)])+    pure (Complete law)+  sites -> fail ("expected two sites: " ++ show sites)++main :: IO ()+main = do+  kernel <- either fail pure (mkKernel (1%8) (pureEvaluator model) guide)+  initial <- initialise kernel (mkStdGen 57341)+  chain <- case initial of+    Initialised value -> pure value+    _ -> fail "initialisation failed"+  chainRef <- newIORef chain+  countsRef <- newIORef Map.empty+  totalsRef <- newIORef Map.empty+  forM_ [1..101000 :: Int] $ \i -> do+    old <- readIORef chainRef+    let from = state (fst (snapshotResult (chainSnapshot old)))+    result <- transition kernel old+    new <- case result of+      Transitioned value _ -> pure value+      _ -> fail "transition failed"+    let to = state (fst (snapshotResult (chainSnapshot new)))+    totals <- readIORef totalsRef+    when (i > 1000 && Map.findWithDefault 0 from totals < 5000) $ do+      modifyIORef' countsRef (Map.insertWith (+) (from,to) (1 :: Int))+      modifyIORef' totalsRef (Map.insertWith (+) from (1 :: Int))+    writeIORef chainRef new+  counts <- readIORef countsRef+  totals <- readIORef totalsRef+  forM_ [0..3] $ \i -> do+    unless (Map.findWithDefault 0 i totals == 5000) (fail "insufficient departures")+    let observed = [Map.findWithDefault 0 (i,j) counts | j <- [0..3]]+        expected = map ((5000 *) . fromRational) (pMixed !! i)+    result <- maybe (fail "chi-squared test needs two bins") pure+      (chi2test 0 (Vector.fromList (zip observed expected)))+    let probability = pValue (testSignificance result)+    putStrLn ("plain -O2 row " ++ show i ++ " counts=" ++ show observed ++ " p=" ++ show probability)+    unless (probability > 0.001) (fail "transition frequencies differ from the reference")
test/ReverseSupport.hs view
@@ -1,4 +1,5 @@-{-# OPTIONS_GHC -fno-cse -fno-full-laziness #-}+{-# OPTIONS_GHC -fno-cse -fno-full-laziness -fno-float-in #-}+-- Avoid the test-module miscompilation matching GHC issue 27886. module ReverseSupport (reverseSupport) where  import Control.DeepSeq (NFData(..))
test/SiteDiscovery.hs view
@@ -2,15 +2,27 @@  import Control.DeepSeq (force) import Control.Exception (SomeException, evaluate, try)-import Control.Monad (forM_, unless)+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 (Tree(..), randomTree)+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@@ -28,9 +40,64 @@     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)) $-      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@@ -52,6 +119,67 @@ 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)@@ -66,7 +194,20 @@  main :: IO () main = do-  unevaluated <- unevaluatedNode-  result <- quickCheckWithResult stdArgs {maxSuccess=200,replay=Just(mkQCGen 20261026,0)} sameSites-  unless unevaluated (fail "A node with an unevaluated label and children was not traversed")-  unless (isSuccess result) (fail "Cached and uncached traversal differ without intervening GC")+  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+  ]