packages feed

raft-consensus-0.1.0.0: tests/Test/Distributed/Consensus/Raft/Properties.hs

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}

module Test.Distributed.Consensus.Raft.Properties
  ( FaultInjection (..),
    allProperties,
  )
where

import Control.Monad (unless, void, when)
import Control.Monitor
  ( allOf,
    assert,
    eventually,
    predicate,
    step,
    whenever,
    (<?>),
  )
import Data.Foldable (for_)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)
import qualified Data.Set as Set
import qualified Data.Text as Text
import Distributed.Consensus.Raft (CommandResponse (..), EventContext (..), LogEntry (LogEntryMembershipChange), LogIndex, RaftTrace (..), SnapshotMetadata (SnapshotMetadata), Term)
import Test.Distributed.Consensus.Raft.Scenario
  ( Scenario,
    clusterMembershipChangeCompleted,
    clusterMembershipChangeInitiated,
    commandReceived,
    commandResponded,
    joinClusterCommandReceived,
    leaveClusterCommandReceived,
    membershipSettled,
  )

-- | Whether we expect the cluster to always respond, or not.
--
-- In general, with faults, Raft clusters are not expected to be live.
-- However, if the fault injector is turned off, we DO expect an answer!
data FaultInjection
  = NoFaultInjection
  | FaultInjection

-- It's still not clear to me why, but without the explicit forall here,
-- RaftTrace events don't get picked up.
allProperties ::
  forall entry node result state.
  ( Eq entry,
    Ord node,
    Show node,
    Show entry
  ) =>
  FaultInjection -> Scenario entry node result state
allProperties faultInjection =
  let -- Properties in Figure 3 of the Raft paper
      coreRaftProperties =
        [ singleLeaderPerTermProperty,
          leaderAppendOnlyProperty,
          logMatchingProperty,
          leaderCompletenessProperty,
          stateMachineSafetyProperty
        ]
      otherProperties =
        [ singleVoteCastPerTermProperty,
          monotonicallyIncreasingTermProperty,
          indexRelationshipProperty,
          monotonicallyIncreasingLastAppliedIndexProperty,
          monotonicallyIncreasingCommitIndexProperty,
          singleConfigurationChangeInFlight
        ]
      noFaultProperties = case faultInjection of
        NoFaultInjection ->
          [ allAcceptedCommandReceiveResponseProperty,
            allAcceptedClusterMembershipRequestsResultInNewClusterConfiguration,
            allAdminRequestToJoinComplete,
            allAdminRequestToLeaveComplete
          ]
        FaultInjection -> []
   in void $
        allOf (coreRaftProperties <> otherProperties <> noFaultProperties)

-- | Ensure that in each term where a leader is elected, no other leader
-- is elected
singleLeaderPerTermProperty :: Scenario entry node result state
singleLeaderPerTermProperty = go mempty <?> "Another leader elected for the same term"
  where
    go seenTerms =
      step
        ()
        ( \case
            LeaderElected (EventContext term _) -> do
              assert
                "Expecting at most one leader per term"
                (Set.notMember term seenTerms)
              go (Set.insert term seenTerms)
            _ -> go seenTerms
        )

-- | Ensure that a node casts at most one vote per term
--
-- Note that under fault conditions, the same vote for the same term may be cast multiple
-- times. I consider this acceptable; votes are idempotent
singleVoteCastPerTermProperty :: (Ord node, Show node) => Scenario entry node result state
singleVoteCastPerTermProperty = go mempty <?> "More than one vote cast per term"
  where
    go votes =
      step
        ()
        ( \case
            VotedFor (EventContext voterTerm voterNode) _ candidate -> do
              assert
                ("Expecting a node to cast at most one vote per term: " <> Text.show votes)
                ( case Map.lookup (voterTerm, voterNode) votes of
                    Nothing -> True
                    Just candidate' -> candidate == candidate' -- allow multiple identical vote for idempotence
                )
              go (Map.insert (voterTerm, voterNode) candidate votes)
            _ -> go votes
        )

-- | Ensure that each node witnesses terms that increase monotonically
monotonicallyIncreasingTermProperty :: (Ord node) => Scenario entry node result state
monotonicallyIncreasingTermProperty = go mempty <?> "Term not increased monotonically"
  where
    go latestKnownTerms =
      step
        ()
        ( \e -> case roleTerm e of
            Nothing -> go latestKnownTerms
            Just (node, newTerm) -> do
              case Map.lookup node latestKnownTerms of
                Nothing -> pure ()
                Just latestTerm ->
                  assert
                    "Expecting terms to increase monotonically"
                    (latestTerm <= newTerm)
              go (Map.insert node newTerm latestKnownTerms)
        )

    roleTerm (LeaderElected (EventContext t n)) = Just (n, t)
    roleTerm (BecameCandidate (EventContext t n)) = Just (n, t)
    roleTerm (BecameFollower (EventContext t n)) = Just (n, t)
    roleTerm _ = Nothing

-- | Ensure that each node's last applied index increases monotonically.
monotonicallyIncreasingLastAppliedIndexProperty :: (Ord node) => Scenario entry node result state
monotonicallyIncreasingLastAppliedIndexProperty = go mempty <?> "Last applied index not increasing monotonically"
  where
    go acc =
      step
        ()
        ( \case
            LastAppliedIndexIncreasedTo (EventContext _ node) lastApplied -> do
              case Map.lookup node acc of
                Nothing -> pure ()
                Just prevLastApplied ->
                  assert
                    "Expecting last applied index to increase monotonically"
                    (prevLastApplied <= lastApplied)

              go (Map.insert node lastApplied acc)
            Crashed node -> go (Map.delete node acc)
            _ -> go acc
        )

-- | Ensure that each node's commit index increases monotonically.
monotonicallyIncreasingCommitIndexProperty :: (Ord node) => Scenario entry node result state
monotonicallyIncreasingCommitIndexProperty = go mempty <?> "Commit index not increasing monotonically"
  where
    go acc =
      step
        ()
        ( \case
            CommitIndexIncreasedTo (EventContext _ node) commitIndex -> do
              case Map.lookup node acc of
                Nothing -> pure ()
                Just prevCommitIndex ->
                  assert
                    "Expecting commit index to increase monotonically"
                    (prevCommitIndex <= commitIndex)

              go (Map.insert node commitIndex acc)
            _ -> go acc
        )

-- | Ensure that every command that was acknowledged by the leader
-- receives a response with the same request ID.
allAcceptedCommandReceiveResponseProperty :: Scenario entry node result state
allAcceptedCommandReceiveResponseProperty = go
  where
    go = void $ whenever commandReceived $ \(_, reqId, _) ->
      let thisCommandResponded =
            commandResponded >>= \(_, MkCommandResponse _result' reqId') ->
              predicate $ \_ -> unless (reqId == reqId') Nothing
       in eventually thisCommandResponded <?> "Never received a response for " <> Text.show reqId

singleConfigurationChangeInFlight :: (Ord node) => Scenario entry node result state
singleConfigurationChangeInFlight = go mempty <?> "A leader appended a configuration change while another was not completed"
  where
    go leaders =
      step
        ()
        ( \case
            LeaderElected (EventContext _ node) -> go (Map.insert node False leaders)
            BecameFollower (EventContext _ node) -> go (Map.delete node leaders)
            BecameCandidate (EventContext _ node) -> go (Map.delete node leaders)
            BecameNonMember (EventContext _ node) -> go (Map.delete node leaders)
            Crashed node -> go (Map.delete node leaders)
            MembershipChangeApplied (EventContext _ node) _ -> go (Map.adjust (const False) node leaders)
            LogEntryAppended (EventContext _ node) _ _ (LogEntryMembershipChange _) ->
              case Map.lookup node leaders of
                Just True -> assert "Expecting at most one unapplied configuration change" False
                Just False -> go (Map.insert node True leaders)
                Nothing -> go leaders
            _ -> go leaders
        )

-- | Ensure that every cluster membership change that's accepted by a leader
-- is seen through by the same leader
allAcceptedClusterMembershipRequestsResultInNewClusterConfiguration :: (Eq node) => Scenario entry node result state
allAcceptedClusterMembershipRequestsResultInNewClusterConfiguration =
  go <?> "An accepted cluster membership request did not result in new configuration"
  where
    go = void $ whenever clusterMembershipChangeInitiated $ \ctx ->
      eventually
        ( clusterMembershipChangeCompleted >>= \ctx' ->
            predicate $ \_ -> unless (ctx == ctx') Nothing
        )

allAdminRequestToJoinComplete :: (Ord node, Show node) => Scenario entry node result state
allAdminRequestToJoinComplete =
  go <?> "A command to join a cluster did not result in new cluster membership"
  where
    -- The authority on whether a node is in the cluster is the
    -- leader that applies the new configuration, not the joining node
    go = void $ whenever joinClusterCommandReceived $ \(EventContext _ nodeJoining) ->
      eventually (membershipSettled (Set.member nodeJoining) nodeJoining)
        <?> "A command to "
        <> Text.show nodeJoining
        <> " to join a cluster did not result in new cluster membership"

allAdminRequestToLeaveComplete :: (Show node, Ord node) => Scenario entry node result state
allAdminRequestToLeaveComplete =
  go
  where
    go = void $ whenever leaveClusterCommandReceived $ \(EventContext _ nodeLeaving) ->
      -- This is quite subtle. Basically, the cluster can replicate, commit, and apply a cluster
      -- configuration change without the node leaving the cluster ever knowing. Consider a cluster
      -- of three nodes [A, B, C], where C is leaving; join configurations [A, B] and [A, B, C] have
      -- quorum with just A and B acknowledging and applying the configuration state.
      --
      -- Therefore, the true mark of whether a node has left a cluster is not from the point-of-view
      -- of that node, but from the point-of-view of the leader, that emits a
      -- 'MembershipChangeApplied'
      eventually (membershipSettled (Set.notMember nodeLeaving) nodeLeaving)
        <?> "A command to "
        <> Text.show nodeLeaving
        <> " to leave a cluster did not result in new cluster membership"

data NodeIndexes
  = MkNodeIndexes
      -- | Last applied index
      !LogIndex
      -- | Commit index
      !LogIndex
      -- | Last log index
      !LogIndex

-- | Ensures that the following relationship holds for each node individually:
--
--    appliex index  <=  commit index  <=  log length
indexRelationshipProperty :: (Ord node) => Scenario entry node result state
indexRelationshipProperty = go mempty <?> "index relationship did not hold"
  where
    checkState node acc =
      case Map.lookup node acc of
        Nothing -> assert "Incomplete state" False
        Just (MkNodeIndexes lastApplied committed lastIndex) -> do
          assert "last_applied_index <= commit_index violated" (lastApplied <= committed)
          assert "commit_index <= last_index violated" (committed <= lastIndex)
    go acc =
      step
        ()
        ( \case
            LastAppliedIndexIncreasedTo (EventContext _ node) lastApplied -> do
              let newAcc =
                    Map.alter
                      ( \case
                          Nothing -> Just (MkNodeIndexes lastApplied 0 0)
                          Just (MkNodeIndexes _ y z) -> Just (MkNodeIndexes lastApplied y z)
                      )
                      node
                      acc
              checkState node newAcc
              go newAcc
            CommitIndexIncreasedTo (EventContext _ node) commitIndex -> do
              let newAcc =
                    Map.alter
                      ( \case
                          Nothing -> Just (MkNodeIndexes 0 commitIndex 0)
                          Just (MkNodeIndexes x _ z) -> Just (MkNodeIndexes x commitIndex z)
                      )
                      node
                      acc
              checkState node newAcc
              go newAcc
            LastLogIndexChangedTo (EventContext _ node) lastLogIndex -> do
              let newAcc =
                    Map.alter
                      ( \case
                          Nothing -> Just (MkNodeIndexes 0 0 lastLogIndex)
                          Just (MkNodeIndexes x y _) -> Just (MkNodeIndexes x y lastLogIndex)
                      )
                      node
                      acc
              checkState node newAcc
              go newAcc
            Crashed node -> go (Map.delete node acc)
            _ -> go acc
        )

-- | If two logs contain an entry with the same index and term, then the
-- logs are identical in all entries up through the given index
logMatchingProperty :: (Ord node, Eq entry) => Scenario entry node result state
logMatchingProperty = go mempty mempty <?> "Conflicting entries appended at the same index and term"
  where
    go logs seen =
      step
        ()
        ( \case
            LogEntryAppended (EventContext _ node) term logIndex entry -> do
              let prefix = Map.takeWhileAntitone (< logIndex) (Map.findWithDefault mempty node logs)

              assert
                "Expecting a contiguous log"
                (logIndex == 1 || Map.member (pred logIndex) prefix)

              case Map.lookup (term, logIndex) seen of
                Nothing -> pure ()
                Just (entry', prefix') -> do
                  assert "Different entries for the same term and log index" (entry == entry')
                  assert
                    ( "Log prefix before term "
                        <> Text.show term
                        <> " and log index "
                        <> Text.show logIndex
                        <> " differs"
                    )
                    (prefix == prefix')

              go
                (Map.insert node (Map.insert logIndex term prefix) logs)
                (Map.insertWith (\_ old -> old) (term, logIndex) (entry, prefix) seen)
            -- A snapshot is special because it serves as the log prefix
            SnapshotApplied (EventContext _ node) (SnapshotMetadata lastLogIndex lastTerm) -> do
              let thisNode = Map.findWithDefault mempty node logs
              case Map.lookup (lastTerm, lastLogIndex) seen of
                Nothing -> do
                  assert
                    ( "Expecting a snapshot at term "
                        <> Text.show lastTerm
                        <> " and log index "
                        <> Text.show lastLogIndex
                    )
                    False
                  go logs seen
                Just (_, prefix) ->
                  let following
                        | Map.lookup lastLogIndex thisNode == Just lastTerm = snd (Map.split lastLogIndex thisNode)
                        | otherwise = mempty
                   in go
                        (Map.insert node (Map.insert lastLogIndex lastTerm prefix <> following) logs)
                        seen
            _ -> go logs seen
        )

-- | If a node has applied a log entry at a given index to its state machine, no other node
-- will ever apply a different log entry for the same index.
stateMachineSafetyProperty :: (Show entry, Eq entry) => Scenario entry node result state
stateMachineSafetyProperty = go mempty <?> "Conflicting entries applied at the same index"
  where
    go acc =
      step
        ()
        ( \case
            LogEntryApplied _ term logIndex entry -> do
              case Map.lookup logIndex acc of
                -- First time this entry has been seen
                Nothing -> go (Map.insert logIndex (term, entry) acc)
                Just (term', entry') ->
                  assert
                    ( "Expecting the same entry to be applied at index "
                        <> Text.show logIndex
                        <> " but saw "
                        <> Text.show (term', entry')
                        <> " and "
                        <> Text.show (term, entry)
                    )
                    (term' == term && entry' == entry)
            _ -> go acc
        )

leaderAppendOnlyProperty :: (Ord node) => Scenario entry node result state
leaderAppendOnlyProperty = go mempty mempty <?> "A leader overwrite or deleted an entry from its own log"
  where
    go !lastIx !leaders =
      step
        ()
        ( \case
            LeaderElected (EventContext _ n) -> go lastIx (Set.insert n leaders)
            BecameFollower (EventContext _ n) -> go lastIx (Set.delete n leaders)
            BecameCandidate (EventContext _ n) -> go lastIx (Set.delete n leaders)
            BecameNonMember (EventContext _ n) -> go lastIx (Set.delete n leaders)
            GracefulShutdown (EventContext _ n) -> go lastIx (Set.delete n leaders)
            Crashed n -> go (Map.delete n lastIx) (Set.delete n leaders)
            LogEntryAppended (EventContext _ n) _ ix _ -> do
              when (n `Set.member` leaders) $
                case Map.lookup n lastIx of
                  Nothing -> pure ()
                  Just prev ->
                    assert
                      ("Leader appended at index " <> Text.show ix <> " but its last index was " <> Text.show prev)
                      (ix == succ prev)
              go (Map.insert n ix lastIx) leaders
            LastLogIndexChangedTo (EventContext _ n) ix -> do
              when (n `Set.member` leaders) $
                case Map.lookup n lastIx of
                  Nothing -> pure ()
                  Just prev ->
                    assert
                      "Leader's last log index regressed"
                      (ix >= prev)
              go (Map.insert n ix lastIx) leaders
            _ -> go lastIx leaders
        )

data NodeLog = MkNodeLog !LogIndex !(Map LogIndex Term)

data Committed
  = NothingCommitted
  | Committed !LogIndex !Term

leaderCompletenessProperty :: (Ord node) => Scenario entry node result state
leaderCompletenessProperty = go mempty NothingCommitted <?> "A leader is missing an entry that was previously committed"
  where
    go !logs !committed =
      step
        ()
        ( \case
            LogEntryAppended (EventContext _ n) t ix _ ->
              go (Map.alter (Just . appendEntry ix t . fromMaybe emptyNodeLog) n logs) committed
            LastLogIndexChangedTo (EventContext _ n) ix ->
              go (Map.adjust (\(MkNodeLog _ runs) -> MkNodeLog ix runs) n logs) committed
            SnapshotApplied (EventContext _ n) (SnapshotMetadata ix t) -> do
              let update l@(MkNodeLog lastIx runs)
                    | termAt ix l == Just t = l
                    | otherwise = MkNodeLog (max ix lastIx) (Map.insert ix t (Map.dropWhileAntitone (<= ix) runs))
               in go (Map.alter (Just . update . fromMaybe emptyNodeLog) n logs) committed
            CommitIndexIncreasedTo (EventContext _ n) c
              | Just t <- Map.lookup n logs >>= termAt c -> case committed of
                  Committed c' t' | c == c' -> do
                    assert ("Index " <> Text.show c <> "committed in two separate terms: " <> Text.show t <> " and " <> Text.show t') (t == t')
                    go logs committed
                  Committed c' _ | c < c' -> go logs committed
                  _ -> go logs (Committed c t)
            LeaderElected (EventContext term n) -> do
              case committed of
                NothingCommitted -> pure ()
                Committed c t -> do
                  let nodeLog = Map.findWithDefault emptyNodeLog n logs
                      MkNodeLog lastIx _ = nodeLog

                  assert ("Incongruent last index for leader of term " <> Text.show term) (lastIx >= c)

                  for_ (termAt c nodeLog) $ \t' ->
                    assert ("Incongruent terms for leader at term " <> Text.show term) (t' == t)

              go logs committed
            _ -> go logs committed
        )
      where
        emptyNodeLog = MkNodeLog 0 mempty

        appendEntry !ix !t (MkNodeLog _ runs) =
          let kept = Map.takeWhileAntitone (< ix) runs
           in MkNodeLog ix $ case Map.lookupMax kept of
                Just (_, t') | t' == t -> kept
                _ -> Map.insert ix t kept

        termAt ix (MkNodeLog _ runs) = snd <$> Map.lookupLE ix runs