{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DerivingStrategies #-}

-- | Time-bounded iteration.
--
-- This is based on simple single-threaded iterative time budgeting
-- and as such not suitable for defensive timeouts since no attempts
-- are made at stopping the computation that breached the time limit.
module Ouroboros.Consensus.Util.TimeBoundedLoop
  ( -- * Iteration
    iterateUntilOrTimeout
  , DoneType (..)
  , StepCount
  , iterateUntilOrTimeout_
  , foldOrTimeout

    -- * Properties
  , propIterImmediateEndOnInit
  , propIterTimeoutOverrunBoundedByOneStep
  , propFoldEmptyListTerminates
  , propFoldStepsMatchConsumed
  , propFoldEndReachedIffConsumedAll
  , propFoldJustFoldl
  ) where

import Cardano.Prelude (lift)
import Control.Monad (unless, when)
import Control.Monad.Class.MonadTime.SI (MonadMonotonicTime (getMonotonicTime), diffTime)
import Control.Monad.Class.MonadTimer.SI (DiffTime, MonadDelay (..))
import Control.Monad.Except (ExceptT, throwError)
import qualified Data.Foldable as Foldable

-- | Why time capped loop stopped.
data DoneType
  = -- | The time budget was exhausted before the end of computation was reached.
    TimeoutReached
  | -- | The computation reached an end before the time budget was exhausted.
    EndReached
  deriving stock (Int -> DoneType -> ShowS
[DoneType] -> ShowS
DoneType -> String
(Int -> DoneType -> ShowS)
-> (DoneType -> String) -> ([DoneType] -> ShowS) -> Show DoneType
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> DoneType -> ShowS
showsPrec :: Int -> DoneType -> ShowS
$cshow :: DoneType -> String
show :: DoneType -> String
$cshowList :: [DoneType] -> ShowS
showList :: [DoneType] -> ShowS
Show, DoneType -> DoneType -> Bool
(DoneType -> DoneType -> Bool)
-> (DoneType -> DoneType -> Bool) -> Eq DoneType
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: DoneType -> DoneType -> Bool
== :: DoneType -> DoneType -> Bool
$c/= :: DoneType -> DoneType -> Bool
/= :: DoneType -> DoneType -> Bool
Eq)

-- | Number of 'stepAction' invocations performed.
type StepCount = Int

-- | @(val, steps, done) <- iterateUntilOrTimeout ttl endReached stepAction initSt@ runs
-- @stepAction@ on a state repeatedly, with @initSt@ as the initial state value, until either
-- @endReached@ holds or the wall-clock budget @ttl@ is exceeded.
-- Returns the final result @val@, the @steps@ it took to compute it and @done@ denoting
-- whether the computation terminated due to the provided end condition or timeout.
--
-- __Strict__ on the accumulator.
--
-- __Single-threaded__: everything runs in one thread.  If @stepAction@ blocks
-- longer than @ttl@, the timeout is detected only on the /next/ iteration —
-- the in-flight call is not cancelled.  The total elapsed time can therefore
-- exceed @ttl@ by at most one step duration (see 'propIterTimeoutOverrunBoundedByOneStep').
--
-- If the @endReached@ holds on the @initSt@ the loop returns immediately with
-- @steps == 0@ and @done == EndReached@ (see 'propIterImmediateEndOnInit').
--
-- Naming reflects https://hackage.haskell.org/package/monad-loops-0.4.3/docs/Control-Monad-Loops.html#v:iterateUntilM
iterateUntilOrTimeout ::
  MonadMonotonicTime m =>
  -- | Wall-clock budget
  DiffTime ->
  -- | End predicate; when @True@, stops with 'EndReached'
  (a -> Bool) ->
  -- | One step of work
  (a -> m a) ->
  -- | Initial state
  a ->
  m (a, StepCount, DoneType)
iterateUntilOrTimeout :: forall (m :: * -> *) a.
MonadMonotonicTime m =>
DiffTime -> (a -> Bool) -> (a -> m a) -> a -> m (a, Int, DoneType)
iterateUntilOrTimeout DiffTime
ttl a -> Bool
endReached a -> m a
stepAction a
initSt = do
  startTime <- m Time
forall (m :: * -> *). MonadMonotonicTime m => m Time
getMonotonicTime
  go 0 startTime initSt
 where
  go :: t -> Time -> a -> m (a, t, DoneType)
go !t
n Time
startTime !a
st = do
    if a -> Bool
endReached a
st
      then (a, t, DoneType) -> m (a, t, DoneType)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (a
st, t
n, DoneType
EndReached)
      else do
        now <- m Time
forall (m :: * -> *). MonadMonotonicTime m => m Time
getMonotonicTime
        if now `diffTime` startTime >= ttl
          then pure (st, n, TimeoutReached)
          else do
            st' <- stepAction st
            go (n + 1) startTime st'

-- | Like 'iterateUntilOrTimeout' but discards the step count and 'DoneType',
-- returning only the final state. Use when you don't need to distinguish a
-- timeout from a normal completion.
iterateUntilOrTimeout_ ::
  MonadMonotonicTime m =>
  -- | Wall-clock budget
  DiffTime ->
  -- | End predicate; when @True@, stops with 'EndReached'
  (a -> Bool) ->
  -- | One step of work
  (a -> m a) ->
  -- | Initial state
  a ->
  m a
iterateUntilOrTimeout_ :: forall (m :: * -> *) a.
MonadMonotonicTime m =>
DiffTime -> (a -> Bool) -> (a -> m a) -> a -> m a
iterateUntilOrTimeout_ DiffTime
ttl a -> Bool
endReached a -> m a
stepAction a
st = (\(a
res, Int
_, DoneType
_) -> a
res) ((a, Int, DoneType) -> a) -> m (a, Int, DoneType) -> m a
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> DiffTime -> (a -> Bool) -> (a -> m a) -> a -> m (a, Int, DoneType)
forall (m :: * -> *) a.
MonadMonotonicTime m =>
DiffTime -> (a -> Bool) -> (a -> m a) -> a -> m (a, Int, DoneType)
iterateUntilOrTimeout DiffTime
ttl a -> Bool
endReached a -> m a
stepAction a
st

-- | @(val, remaining, steps, done) <- foldOrTimeout ttl foldAction initSt xs@ runs a time capped
-- left fold using 'iterateUntilOrTimeout'.
-- Returns the final result in @val@, the @remaining@ elements of @xs@ that weren't processed,
-- the @steps@ it took to compute it and whether the
-- computation terminated due to the input @xs@ being fully traversed or @ttl@ timeout.
--
-- __Strict__ on the accumulator.
--
-- Naming reflects https://hackage-content.haskell.org/package/base-4.22.0.0/docs/Control-Monad.html#v:foldM
foldOrTimeout ::
  MonadMonotonicTime m =>
  -- | Wall-clock budget
  DiffTime ->
  -- | Fold action applied to each element
  (b -> a -> m b) ->
  -- | Initial accumulator
  b ->
  -- | Elements to fold over
  [a] ->
  m (b, [a], StepCount, DoneType)
foldOrTimeout :: forall (m :: * -> *) b a.
MonadMonotonicTime m =>
DiffTime
-> (b -> a -> m b) -> b -> [a] -> m (b, [a], Int, DoneType)
foldOrTimeout DiffTime
ttl b -> a -> m b
foldAction b
initSt [a]
xs =
  (\(([a]
xsLeft, b
finalSt), Int
steps, DoneType
doneType) -> (b
finalSt, [a]
xsLeft, Int
steps, DoneType
doneType))
    ((([a], b), Int, DoneType) -> (b, [a], Int, DoneType))
-> m (([a], b), Int, DoneType) -> m (b, [a], Int, DoneType)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> DiffTime
-> (([a], b) -> Bool)
-> (([a], b) -> m ([a], b))
-> ([a], b)
-> m (([a], b), Int, DoneType)
forall (m :: * -> *) a.
MonadMonotonicTime m =>
DiffTime -> (a -> Bool) -> (a -> m a) -> a -> m (a, Int, DoneType)
iterateUntilOrTimeout
      DiffTime
ttl
      (\([a]
xsLeft, !b
_st) -> [a] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [a]
xsLeft)
      ( \([a]
xsLeft, !b
st) -> case [a]
xsLeft of
          (a
x : [a]
xsLeft') -> do
            st' <- b -> a -> m b
foldAction b
st a
x
            return (xsLeft', st')
          [] -> ([a], b) -> m ([a], b)
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return ([a]
xsLeft, b
st) -- unreachable: end predicate fires first
      )
      ([a]
xs, b
initSt)

{-------------------------------------------------------------------------------
  Properties
-------------------------------------------------------------------------------}

type IterResult b = (b, StepCount, DoneType)

-- | If 'endReached' holds on the initial state, 'iterateUntilOrTimeout' returns
-- immediately with zero steps and 'EndReached', regardless of the budget.
propIterImmediateEndOnInit ::
  (MonadMonotonicTime m, Eq a) =>
  DiffTime ->
  (a -> m a) ->
  a ->
  ExceptT (String, IterResult a) m (IterResult a)
propIterImmediateEndOnInit :: forall (m :: * -> *) a.
(MonadMonotonicTime m, Eq a) =>
DiffTime
-> (a -> m a)
-> a
-> ExceptT (String, IterResult a) m (IterResult a)
propIterImmediateEndOnInit DiffTime
ttl a -> m a
stepAction a
initSt = do
  res@(val, steps, doneType) <- m (IterResult a) -> ExceptT (String, IterResult a) m (IterResult a)
forall (m :: * -> *) a.
Monad m =>
m a -> ExceptT (String, IterResult a) m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (m (IterResult a)
 -> ExceptT (String, IterResult a) m (IterResult a))
-> m (IterResult a)
-> ExceptT (String, IterResult a) m (IterResult a)
forall a b. (a -> b) -> a -> b
$ DiffTime -> (a -> Bool) -> (a -> m a) -> a -> m (IterResult a)
forall (m :: * -> *) a.
MonadMonotonicTime m =>
DiffTime -> (a -> Bool) -> (a -> m a) -> a -> m (a, Int, DoneType)
iterateUntilOrTimeout DiffTime
ttl (Bool -> a -> Bool
forall a b. a -> b -> a
const Bool
True) a -> m a
stepAction a
initSt
  unless (steps == 0) $ throwError $ ("steps must be zero", res)
  unless (doneType == EndReached) $ throwError $ ("done must be end reached", res)
  unless (val == initSt) $ throwError $ ("val must be initial st", res)
  return res

-- | The total elapsed time never exceeds @ttl + stepDuration@: the timeout is
-- detected at the top of the loop, so at most one in-flight step can overshoot
-- before the budget breach is observed.
propIterTimeoutOverrunBoundedByOneStep ::
  MonadDelay m =>
  DiffTime ->
  DiffTime ->
  ExceptT (String, (DiffTime, IterResult ())) m (IterResult ())
propIterTimeoutOverrunBoundedByOneStep :: forall (m :: * -> *).
MonadDelay m =>
DiffTime
-> DiffTime
-> ExceptT (String, (DiffTime, IterResult ())) m (IterResult ())
propIterTimeoutOverrunBoundedByOneStep DiffTime
ttl DiffTime
stepActionDelay = do
  start <- m Time -> ExceptT (String, (DiffTime, IterResult ())) m Time
forall (m :: * -> *) a.
Monad m =>
m a -> ExceptT (String, (DiffTime, IterResult ())) m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift m Time
forall (m :: * -> *). MonadMonotonicTime m => m Time
getMonotonicTime
  res@(_, steps, doneType) <-
    lift $
      iterateUntilOrTimeout
        ttl
        (const False)
        (const $ threadDelay stepActionDelay)
        ()
  end <- lift getMonotonicTime
  let duration = Time
end Time -> Time -> DiffTime
`diffTime` Time
start

  unless (doneType == TimeoutReached) $
    throwError $
      ("done type must be due to timeout", (duration, res))
  unless (duration >= max ttl (fromIntegral steps * stepActionDelay)) $
    throwError $
      ( "duration must be equal or longer than max between ttl and steps * stepActionDelay"
      , (duration, res)
      )
  unless (duration <= ttl + stepActionDelay) $
    throwError $
      ("duration must be equal or shorter than ttl + stepActionDelay", (duration, res))

  return res

type FoldResult b a = (b, [a], StepCount, DoneType)

-- | 'foldOrTimeout' on an empty list terminates immediately: no change, zero steps,
-- 'EndReached', and an empty remainder.
propFoldEmptyListTerminates ::
  (MonadMonotonicTime m, Eq b) =>
  DiffTime ->
  (b -> a -> m b) ->
  b ->
  ExceptT (String, FoldResult b a) m (FoldResult b a)
propFoldEmptyListTerminates :: forall (m :: * -> *) b a.
(MonadMonotonicTime m, Eq b) =>
DiffTime
-> (b -> a -> m b)
-> b
-> ExceptT (String, FoldResult b a) m (FoldResult b a)
propFoldEmptyListTerminates DiffTime
ttl b -> a -> m b
foldAction b
initSt = do
  res@(val, remaining, steps, done) <- m (FoldResult b a)
-> ExceptT (String, FoldResult b a) m (FoldResult b a)
forall (m :: * -> *) a.
Monad m =>
m a -> ExceptT (String, FoldResult b a) m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (m (FoldResult b a)
 -> ExceptT (String, FoldResult b a) m (FoldResult b a))
-> m (FoldResult b a)
-> ExceptT (String, FoldResult b a) m (FoldResult b a)
forall a b. (a -> b) -> a -> b
$ DiffTime -> (b -> a -> m b) -> b -> [a] -> m (FoldResult b a)
forall (m :: * -> *) b a.
MonadMonotonicTime m =>
DiffTime
-> (b -> a -> m b) -> b -> [a] -> m (b, [a], Int, DoneType)
foldOrTimeout DiffTime
ttl b -> a -> m b
foldAction b
initSt []
  unless (null remaining) $ throwError $ ("remaining must be empty", res)
  unless (steps == 0) $ throwError $ ("steps must be zero", res)
  unless (done == EndReached) $ throwError $ ("done must be EndReached", res)
  unless (val == initSt) $ throwError $ ("val must be initSt", res)
  return res

-- | The step count always equals the number of elements consumed.
propFoldStepsMatchConsumed ::
  MonadMonotonicTime m =>
  DiffTime ->
  (b -> a -> m b) ->
  b ->
  [a] ->
  ExceptT (String, FoldResult b a) m (FoldResult b a)
propFoldStepsMatchConsumed :: forall (m :: * -> *) b a.
MonadMonotonicTime m =>
DiffTime
-> (b -> a -> m b)
-> b
-> [a]
-> ExceptT (String, FoldResult b a) m (FoldResult b a)
propFoldStepsMatchConsumed DiffTime
ttl b -> a -> m b
foldAction b
initSt [a]
xs = do
  res@(_, remaining, steps, _) <- m (FoldResult b a)
-> ExceptT (String, FoldResult b a) m (FoldResult b a)
forall (m :: * -> *) a.
Monad m =>
m a -> ExceptT (String, FoldResult b a) m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (m (FoldResult b a)
 -> ExceptT (String, FoldResult b a) m (FoldResult b a))
-> m (FoldResult b a)
-> ExceptT (String, FoldResult b a) m (FoldResult b a)
forall a b. (a -> b) -> a -> b
$ DiffTime -> (b -> a -> m b) -> b -> [a] -> m (FoldResult b a)
forall (m :: * -> *) b a.
MonadMonotonicTime m =>
DiffTime
-> (b -> a -> m b) -> b -> [a] -> m (b, [a], Int, DoneType)
foldOrTimeout DiffTime
ttl b -> a -> m b
foldAction b
initSt [a]
xs
  unless (steps == length xs - length remaining) $
    throwError $
      ("steps must be length xs - length remaining", res)
  return res

-- | 'EndReached' if and only if the entire input was consumed.
propFoldEndReachedIffConsumedAll ::
  MonadMonotonicTime m =>
  DiffTime ->
  (b -> a -> m b) ->
  b ->
  [a] ->
  ExceptT (String, FoldResult b a) m (FoldResult b a)
propFoldEndReachedIffConsumedAll :: forall (m :: * -> *) b a.
MonadMonotonicTime m =>
DiffTime
-> (b -> a -> m b)
-> b
-> [a]
-> ExceptT (String, FoldResult b a) m (FoldResult b a)
propFoldEndReachedIffConsumedAll DiffTime
ttl b -> a -> m b
foldAction b
initSt [a]
xs = do
  res@(_, remaining, _, done) <- m (FoldResult b a)
-> ExceptT (String, FoldResult b a) m (FoldResult b a)
forall (m :: * -> *) a.
Monad m =>
m a -> ExceptT (String, FoldResult b a) m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (m (FoldResult b a)
 -> ExceptT (String, FoldResult b a) m (FoldResult b a))
-> m (FoldResult b a)
-> ExceptT (String, FoldResult b a) m (FoldResult b a)
forall a b. (a -> b) -> a -> b
$ DiffTime -> (b -> a -> m b) -> b -> [a] -> m (FoldResult b a)
forall (m :: * -> *) b a.
MonadMonotonicTime m =>
DiffTime
-> (b -> a -> m b) -> b -> [a] -> m (b, [a], Int, DoneType)
foldOrTimeout DiffTime
ttl b -> a -> m b
foldAction b
initSt [a]
xs
  when (done == EndReached) $
    unless (null remaining) $
      throwError $
        ("remaining must be empty when end is reached", res)
  when (null remaining) $
    unless (done == EndReached) $
      throwError $
        ("done must be EndReached when all elements consumed", res)
  return res

-- | When 'foldAction' is pure then it's just a 'Foldable.foldl\'' on processed @xs@.
propFoldJustFoldl ::
  (MonadMonotonicTime m, Eq b) =>
  DiffTime ->
  (b -> a -> b) ->
  b ->
  [a] ->
  ExceptT (String, FoldResult b a) m (FoldResult b a)
propFoldJustFoldl :: forall (m :: * -> *) b a.
(MonadMonotonicTime m, Eq b) =>
DiffTime
-> (b -> a -> b)
-> b
-> [a]
-> ExceptT (String, FoldResult b a) m (FoldResult b a)
propFoldJustFoldl DiffTime
ttl b -> a -> b
foldFn b
initSt [a]
xs = do
  res@(val, _remaining, steps, _done) <-
    m (FoldResult b a)
-> ExceptT (String, FoldResult b a) m (FoldResult b a)
forall (m :: * -> *) a.
Monad m =>
m a -> ExceptT (String, FoldResult b a) m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (m (FoldResult b a)
 -> ExceptT (String, FoldResult b a) m (FoldResult b a))
-> m (FoldResult b a)
-> ExceptT (String, FoldResult b a) m (FoldResult b a)
forall a b. (a -> b) -> a -> b
$ DiffTime -> (b -> a -> m b) -> b -> [a] -> m (FoldResult b a)
forall (m :: * -> *) b a.
MonadMonotonicTime m =>
DiffTime
-> (b -> a -> m b) -> b -> [a] -> m (b, [a], Int, DoneType)
foldOrTimeout DiffTime
ttl (\b
st a
x -> b -> m b
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (b -> m b) -> b -> m b
forall a b. (a -> b) -> a -> b
$ b -> a -> b
foldFn b
st a
x) b
initSt [a]
xs
  unless (val == Foldable.foldl' foldFn initSt (Prelude.take steps xs)) $
    throwError $
      ("val must be foldl over processed xs", res)
  return res