raft-consensus 0.1.0.0 → 0.1.1.0
raw patch · 7 files changed
+470/−175 lines, 7 filesPVP: major bump suggested
API removals or changes: PVP suggests a major version bump
API changes (from Hackage documentation)
+ Distributed.Consensus.Raft: EventLogPersisted :: !Term -> !LogIndex -> Event entry node result state
+ Distributed.Consensus.Raft: [aerPrevLogIndex] :: AppendEntriesResult node result -> !LogIndex
- Distributed.Consensus.Raft: AppendEntriesResult :: !Term -> !node -> !Bool -> !LogIndex -> !ReadOnlySequenceNum -> AppendEntriesResult node result
+ Distributed.Consensus.Raft: AppendEntriesResult :: !Term -> !node -> !Bool -> !LogIndex -> !LogIndex -> !ReadOnlySequenceNum -> AppendEntriesResult node result
Files
- CHANGELOG.md +11/−0
- bench/Main.hs +230/−101
- raft-consensus.cabal +1/−1
- src/Distributed/Consensus/Raft/Algorithm.hs +67/−27
- src/Distributed/Consensus/Raft/Implementation.hs +18/−0
- src/Distributed/Consensus/Raft/Transformer.hs +84/−38
- src/Distributed/Consensus/Raft/Transformer/Definition.hs +59/−8
CHANGELOG.md view
@@ -1,5 +1,16 @@ # Revision history for raft-consensus +## 0.1.1.0 -- 2026-11-30++* Improved that latency of service read-only requests. In version 0.1.0.0, a read-only request+ could never be served faster than a heartbeat period. Starting with version 0.1.1.0, read-only+ requests trigger a heartbeat when appropriate, cutting latency by up to 40% (#13).+* Optimistically assume success when replicating to followers, which is almost always right,+ and reduces the amount of replicating done. This can lead to a 2x increased throughput+ in the extreme case of a very fast network (in which case replication is bottlednecked by persistence) (#16).+* Persisting log entries and replicating across the cluster is now performed in parallel, which can+ increase throughput by a factor of 2x under load (#15).+ ## 0.1.0.0 -- 2026-11-26 * First version. Released on an unsuspecting world.
bench/Main.hs view
@@ -10,12 +10,13 @@ module Main (main) where import Control.Concurrent (threadDelay)-import Control.Concurrent.Async (async, cancel, forConcurrently_)+import Control.Concurrent.Async (Async, async, cancel, forConcurrently_, link) import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar) import Control.Concurrent.STM (TQueue, atomically, flushTQueue, newTQueueIO, readTQueue, retry, writeTQueue) import Control.DeepSeq (NFData)-import Control.Monad (forever, replicateM, (>=>))+import Control.Monad (forever, unless) import Data.Functor ((<&>))+import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IntMap import Data.List.NonEmpty (NonEmpty, nonEmpty)@@ -24,11 +25,11 @@ import Data.Set (Set) import qualified Data.Set as Set import Data.Word (Word64)-import Distributed.Consensus.Raft (Config (..), Implementation (..), Microseconds, Networking (..), RPC, RPCResult, StateMachineStep (..), ephemeralPersistence, runRaftServer)+import Distributed.Consensus.Raft (Config (..), Implementation (..), Microseconds, Networking (..), Persistence (..), RPC, RPCResult, StateMachineStep (..), ephemeralPersistence, runRaftServer) import qualified Distributed.Consensus.Raft as Raft import Distributed.Consensus.Raft.Admin (AdminRequest, AdminResponse) import Distributed.Consensus.Raft.Client- ( ClientError,+ ( ClientError (..), ClientImplementation (..), ClientRequest, ClientResponse,@@ -38,67 +39,119 @@ withClientSession, ) import GHC.Generics (Generic)-import Test.Tasty (withResource)-import Test.Tasty.Bench (bench, bgroup, defaultMain, nfIO)+import Test.Tasty (TestTree, localOption, withResource)+import Test.Tasty.Bench (TimeMode (WallTime), bench, bgroup, defaultMain, nfIO) main :: IO () main = do defaultMain- [ withResource startCluster stopCluster $ \getClusterHandle ->+ [ localOption WallTime $ bgroup "Benchmark"- [ unloadedLatency getClusterHandle,- bgroup- "Unloaded throughput"- [ unloadedThroughput getClusterHandle 1,- unloadedThroughput getClusterHandle 10,- unloadedThroughput getClusterHandle 100- ]+ [ benchmarksByTechnology storage network+ | storage <- [EphemeralStorage, SimulatedDisk 1_000],+ network <- [Instant, SimulatedLatency 1_000] ] ]++totalCommands :: Int+totalCommands = 128++clientCounts :: [Int]+clientCounts = [1, 8, 32, 128]++sustainedCommandsPerClient :: Int+sustainedCommandsPerClient = 20++sustainedClientCounts :: [Int]+sustainedClientCounts = [8, 32, 128, 512]++maxClients :: Int+maxClients = maximum (clientCounts ++ sustainedClientCounts)++data Workload+ = -- | Only reads+ Reads+ | -- | Only mutation+ Writes+ deriving (Show)++runWorkload :: Cluster -> Workload -> Int -> Int -> IO ()+runWorkload cluster w nClients total =+ forConcurrently_ (zip [0 ..] (take nClients cluster.clients)) $ \(c, runCommand) ->+ mapM_ (runCommand . workloadCommand) [c, c + nClients .. total - 1] where- unloadedLatency getClusterHandle =- bench "Unloaded latency " $ nfIO $ do- cluster <- getClusterHandle- cluster.runRequest (Get 'a')+ workloadCommand ix =+ case w of+ Reads -> Get key+ Writes -> Insert key ix+ where+ key = toEnum (fromEnum 'a' + ix `mod` 128) - unloadedThroughput getClusterHandle batchSize =- bench (show batchSize <> " commands") $- nfIO $- do- cluster <- getClusterHandle- replicateM batchSize (cluster.runRequest (Get 'a'))+benchmarksByTechnology :: Storage -> Network -> TestTree+benchmarksByTechnology storage network =+ withResource (startCluster storage network) stopCluster $ \getCluster ->+ bgroup+ (show storage <> ", " <> show network)+ [ bgroup+ "Unloaded latency (1 client)"+ [ bench (show workload) $ nfIO $ do+ cluster <- getCluster+ runWorkload cluster workload 1 1+ | workload <- [Reads, Writes]+ ],+ bgroup+ (show totalCommands <> " commands")+ [ bgroup+ (show workload)+ [ bench (show nClients <> " clients") $ nfIO $ do+ cluster <- getCluster+ runWorkload cluster workload nClients totalCommands+ | nClients <- clientCounts+ ]+ | workload <- [Reads, Writes]+ ],+ bgroup+ ("Sustained load " <> show sustainedCommandsPerClient <> " commands per client")+ [ bgroup+ (show workload)+ [ bench (show nClients <> " clients") $ nfIO $ do+ cluster <- getCluster+ runWorkload cluster workload nClients (nClients * sustainedCommandsPerClient)+ | nClients <- sustainedClientCounts+ ]+ | workload <- [Reads, Writes]+ ]+ ] data Cluster = Cluster- { runRequest :: Command -> IO Result,+ { clients :: [Command -> IO Result], runShutDown :: IO () } -startCluster :: IO Cluster-startCluster = do- harness <- benchHarness clusterScenario+startCluster :: Storage -> Network -> IO Cluster+startCluster storage network = do+ harness <- benchHarness storage network clusterScenario serversTid <- async (runServers harness)+ link serversTid - runnerVar <- newEmptyMVar- sessionTid <-- async $- withClient harness $ \runClientRequest -> do- putMVar runnerVar runClientRequest- forever (threadDelay 1_000_000)- runClientRequest <- takeMVar runnerVar+ firstLeaderRef <- newIORef 0+ (firstTid, firstClient) <- startClient harness firstLeaderRef (clientNodeId 0)+ -- Blocking here until the leader is known+ _ <- firstClient (Get 'a') - leader <- waitUntilLeaderElected runClientRequest+ leader <- readIORef firstLeaderRef+ others <-+ traverse+ (\i -> newIORef leader >>= \ref -> startClient harness ref (clientNodeId i))+ [1 .. maxClients - 1]+ pure $ Cluster- { runRequest = runClientRequest leader >=> either (fail . show) (pure . snd),- runShutDown = cancel sessionTid >> cancel serversTid+ { clients = firstClient : map snd others,+ runShutDown = mapM_ cancel (firstTid : map fst others) >> cancel serversTid } where- waitUntilLeaderElected runClientRequest =- runClientRequest 0 (Get 'a') >>= \case- Left _ -> threadDelay 10_000 >> waitUntilLeaderElected runClientRequest- Right (leader, _) -> pure leader- runServers :: Harness -> IO () runServers harness = forConcurrently_ (IntMap.elems harness.clusterServers) $ \server ->@@ -108,6 +161,25 @@ mempty server.sSpec + startClient :: Harness -> IORef Node -> Node -> IO (Async (), Command -> IO Result)+ startClient harness leaderRef self = do+ runnerVar <- newEmptyMVar+ tid <- async $+ withClient harness self $ \runClientRequest -> do+ putMVar runnerVar (request runClientRequest)+ forever (threadDelay 1_000_000)++ link tid++ (tid,) <$> takeMVar runnerVar+ where+ request run command = do+ leader <- readIORef leaderRef+ run leader command >>= \case+ Right (actualLeader, result) -> writeIORef leaderRef actualLeader >> pure result+ Left (Redirect actualLeader) -> writeIORef leaderRef actualLeader >> request run command+ Left _ -> threadDelay 1_000 >> request run command+ stopCluster :: Cluster -> IO () stopCluster = runShutDown @@ -140,34 +212,17 @@ type Mailbox a = IntMap (TQueue a) -data NetworkFabric- = MkNetworkFabric- { rpcMailbox :: Mailbox (RPC Command Node State),- rpcResultsMailbox :: Mailbox (RPCResult Node Result),- requestsMailbox :: Mailbox (ClientRequest Command Node),- responsesMailbox :: Mailbox (ClientResponse Node Result),- adminMailbox :: Mailbox (AdminRequest Node),- adminResponsesMailbox :: Mailbox (AdminResponse Node)- }--newNetworkFabric :: Set Node -> IO NetworkFabric-newNetworkFabric nodes =- MkNetworkFabric- <$> newMailbox- <*> newMailbox- <*> newMailbox- <*> newMailbox- <*> newMailbox- <*> newMailbox- where- newMailbox =- IntMap.fromList- <$> traverse- (\n -> (fromIntegral n,) <$> newTQueueIO)- (Set.toList nodes)--mkServer :: NetworkFabric -> Microseconds -> Microseconds -> Microseconds -> Word64 -> Node -> Server-mkServer network hbto etolb etoub seed node =+mkServer ::+ Storage ->+ Network ->+ NetworkFabric ->+ Microseconds ->+ Microseconds ->+ Microseconds ->+ Word64 ->+ Node ->+ Server+mkServer storage network fabric hbto etolb etoub seed node = MkServer { sConfig = MkConfig@@ -179,19 +234,9 @@ }, sSpec = Implementation- { persistence = ephemeralPersistence,+ { persistence = storagePersistence storage, stateMachine = step,- networking =- Networking- { sendRPC = send network.rpcMailbox,- sendRPCResult = send network.rpcResultsMailbox,- sendClientResponse = send network.responsesMailbox,- sendAdminResponse = send network.adminResponsesMailbox,- receiveRPC = receive network.rpcMailbox node,- receiveRPCResult = receive network.rpcResultsMailbox node,- receiveClientRequests = receiveAll network.requestsMailbox node,- receiveAdminRequest = receive network.adminMailbox node- },+ networking = networkingImplementation node network fabric, tracer = \_ -> pure () } }@@ -203,60 +248,66 @@ -- the whole benchmark: see 'withClientSession'. withClient :: forall b.+ Node -> ((Node -> Command -> IO (Either (ClientError Command Node) (Node, Result))) -> IO b) -> IO b } +clientNodeId :: Int -> Node+clientNodeId x = Node $ clusterScenario.numInitialClusterNodes + 1 + x -- +1 for the admin node+ benchHarness ::+ Storage ->+ Network -> ScenarioInputs -> IO Harness benchHarness+ storage+ network (ScenarioInputs hb etlb etup s numClusterNodes) = do networkFabric <- newNetworkFabric $ mconcat [ Set.fromList (fromIntegral <$> serverNodes),- Set.singleton clientNode,+ Set.fromList (clientNodeId <$> [0 .. maxClients - 1]), Set.singleton adminNode ] let mkServer' :: Word64 -> Node -> Server- mkServer' = mkServer networkFabric hb etlb etup+ mkServer' = mkServer storage network networkFabric hb etlb etup pure $ MkHarness { clusterServers = IntMap.fromList $ map (\(serverSeed, n) -> (n, mkServer' serverSeed (fromIntegral n))) serverNodesWithSeeds,- withClient = \useClient ->- withClientSession clientNode (clientSpec networkFabric) $ \runSession ->+ withClient = \clientNode useClient ->+ withClientSession clientNode (clientSpec networkFabric clientNode) $ \runSession -> useClient (\leader comm -> runSession (newRequest comm >>= sendClientRequest maxBound leader)) } where adminNode = -1- clientNode = Node $ numClusterNodes + 1 serverNodes = [0 .. numClusterNodes - 1] serverNodesWithSeeds = zip (take numClusterNodes s) serverNodes - clientSpec network =+ clientSpec fabric clientNode = ClientImplementation- { sendRequest = send network.requestsMailbox,+ { sendRequest =+ -- No latency because that's not due to the cluster+ send 0 fabric.requestsMailbox, receiveResponse =- receive network.responsesMailbox clientNode,+ receive fabric.responsesMailbox clientNode, -- We should generate a random session ID in normal circumstances, -- but for a benchmark this doesn't matter generateSessionId = pure . sessionId 0 . fromIntegral } -simulatedNetworkLatency :: IO ()-simulatedNetworkLatency = threadDelay 1_000--send :: IntMap (TQueue a) -> Node -> a -> IO ()-send mailbox node message =+send :: Int -> IntMap (TQueue a) -> Node -> a -> IO ()+send latency mailbox node message = case IntMap.lookup (fromIntegral node) mailbox of Nothing -> error $ "Mailbox badly configures: missing node " <> show node- Just queue -> simulatedNetworkLatency >> atomically (writeTQueue queue message)+ Just queue -> threadDelay latency >> atomically (writeTQueue queue message) receive :: IntMap (TQueue a) -> Node -> IO a receive mailbox node =@@ -274,6 +325,84 @@ Nothing -> retry Just xs -> pure xs +-- Storage technologies++data Storage+ = EphemeralStorage+ | SimulatedDisk Microseconds++instance Show Storage where+ show EphemeralStorage = "ephemeral storage"+ show (SimulatedDisk us) =+ "persistence latency = "+ <> show (fromIntegral us `div` (1000 :: Int))+ <> "ms"++storagePersistence :: Storage -> Persistence Command Node State IO+storagePersistence EphemeralStorage = ephemeralPersistence+storagePersistence (SimulatedDisk latency) =+ let durableWrite = threadDelay (fromIntegral latency)+ in ephemeralPersistence+ { writeLogEntry = \_ entries -> unless (null entries) durableWrite,+ truncateLogEntriesFrom = \_ _ -> durableWrite,+ writeTerm = \_ _ -> durableWrite,+ writeVotedFor = \_ _ _ -> durableWrite,+ writeSnapshot = \_ _ -> durableWrite,+ writeCommitIndex = \_ _ -> pure () -- does not need to be durable+ }++-- Network technologies+data Network+ = Instant+ | SimulatedLatency Microseconds++instance Show Network where+ show Instant = "instant network"+ show (SimulatedLatency us) =+ "network latency = "+ <> show (fromIntegral us `div` (1000 :: Int))+ <> "ms"++networkingImplementation :: Node -> Network -> NetworkFabric -> Networking Command Node Result State IO+networkingImplementation node network fabric =+ let latency = case network of Instant -> 0; SimulatedLatency lats -> fromIntegral lats+ in Networking+ { sendRPC = send latency fabric.rpcMailbox,+ sendRPCResult = send latency fabric.rpcResultsMailbox,+ sendClientResponse = send 0 fabric.responsesMailbox, -- latency to/from client is not counter+ sendAdminResponse = send 0 fabric.adminResponsesMailbox,+ receiveRPC = receive fabric.rpcMailbox node,+ receiveRPCResult = receive fabric.rpcResultsMailbox node,+ receiveClientRequests = receiveAll fabric.requestsMailbox node,+ receiveAdminRequest = receive fabric.adminMailbox node+ }++data NetworkFabric+ = MkNetworkFabric+ { rpcMailbox :: Mailbox (RPC Command Node State),+ rpcResultsMailbox :: Mailbox (RPCResult Node Result),+ requestsMailbox :: Mailbox (ClientRequest Command Node),+ responsesMailbox :: Mailbox (ClientResponse Node Result),+ adminMailbox :: Mailbox (AdminRequest Node),+ adminResponsesMailbox :: Mailbox (AdminResponse Node)+ }++newNetworkFabric :: Set Node -> IO NetworkFabric+newNetworkFabric nodes =+ MkNetworkFabric+ <$> newMailbox+ <*> newMailbox+ <*> newMailbox+ <*> newMailbox+ <*> newMailbox+ <*> newMailbox+ where+ newMailbox =+ IntMap.fromList+ <$> traverse+ (\n -> (fromIntegral n,) <$> newTQueueIO)+ (Set.toList nodes)+ -- Simple key-value store newtype Node = Node Int@@ -282,13 +411,13 @@ type State = Map Char Int data Command- = Insert Char Int- | Delete Char- | Get Char+ = Insert !Char !Int+ | Delete !Char+ | Get !Char deriving (Eq, Ord, Show) data Result- = Value Int+ = Value !Int | Ok | Err deriving (Eq, Show, Generic)
raft-consensus.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.4 name: raft-consensus-version: 0.1.0.0+version: 0.1.1.0 synopsis: Haskell implementation of the Raft consensus protocol -- description: homepage: https://github.com/LaurentRDC/distributed-consensus
src/Distributed/Consensus/Raft/Algorithm.hs view
@@ -11,19 +11,21 @@ where import Control.Concurrent.Class.MonadMVar (MonadMVar, putMVar)-import Control.Concurrent.Class.MonadSTM (atomically, readTQueue, tryPeekTQueue, writeTQueue)-import Control.Monad (forever, unless, when)+import Control.Concurrent.Class.MonadSTM (atomically, flushTQueue, readTQueue, retry, tryPeekTQueue, writeTQueue)+import Control.Monad (forever, unless, void, when) import Control.Monad.Class.MonadAsync (MonadAsync, async, cancel, link) import Control.Monad.Class.MonadFork (MonadFork, labelThisThread) import Control.Monad.Class.MonadThrow (MonadMask) import Control.Monad.Class.MonadTimer (MonadDelay) import Control.Monad.Trans.Class (lift) import Data.Foldable (for_, toList, traverse_)+import Data.Function ((&)) import Data.Functor ((<&>)) import Data.List.NonEmpty (NonEmpty) import qualified Data.List.NonEmpty as NonEmpty import qualified Data.Map.Strict as Map import Data.Maybe (fromMaybe)+import Data.Semigroup (sconcat) import qualified Data.Set as Set import qualified Distributed.Consensus.Raft.Admin as Admin import Distributed.Consensus.Raft.Domain@@ -60,6 +62,7 @@ import Distributed.Consensus.Raft.Messaging (Request (..), Response (..)) import Distributed.Consensus.Raft.Transformer ( Config (..),+ PersistenceBatch (..), RaftT, acceptClientRequests, appendLogEntries,@@ -68,6 +71,7 @@ applySnapshot, becomeCandidate, becomeFollower,+ broadcastForPendingReads, checkElection, clusterConfiguration, commandLog,@@ -76,12 +80,16 @@ currentLeader, currentSnapshot, dequeueEvent,+ durableIndex, enqueueEvent, eventQueue, exitLock,+ followerProgress, implementation, isClusterMember, leaderStepDown,+ matchIndex,+ newFollowerState, nextIndex, peers, pendingClusterMembershipChanges,@@ -89,7 +97,9 @@ pendingReadRequests, pendingReadSequenceNum, persistSnapshot,+ persistenceQueue, proposeClusterMembership,+ replicating, resetElectionTimer, resetHeartBeatTimer, restoreState,@@ -105,10 +115,11 @@ updateTerm, voteFor, votedFor,+ whenRole, yesVotes, ) import qualified Distributed.Consensus.Raft.Transformer as Transformer-import Lens.Micro.Platform (at, filtered, traversed, use, view, (%=), (.=))+import Lens.Micro.Platform (at, filtered, traversed, use, view, (%=), (.=), (.~), (^.)) server :: ( Ord node,@@ -122,6 +133,7 @@ server = do impl <- view implementation queue <- view eventQueue+ writeQueue <- view persistenceQueue t1 <- lift $ async $ receiveRPCsThread impl queue t2 <- lift $ async $ receiveRPCResultsThread impl queue@@ -130,11 +142,15 @@ let receiveLoops = [t1, t2, t3, t4] for_ receiveLoops (lift . link) + s <- self+ w <- lift $ async $ persistenceThread s impl queue writeQueue+ lift $ link w+ -- There are some initialization steps which require the configuration. -- Instead of coupling 'initialRaftState' with the configuration, -- we perform some initialization here. ps <- peers- nextIndex .= Map.fromSet (const 0) ps+ followerProgress .= Map.fromSet (const (newFollowerState 0)) ps restoreState @@ -179,7 +195,20 @@ let recv = impl.networking.receiveAdminRequest forever $ recv >>= atomically . writeTQueue queue . EventAdminRequest+ persistenceThread node impl queue writeQueue = do+ labelThisThread "persistence"+ let write = impl.persistence.writeLogEntry node+ forever $ do+ MkPersistenceBatch t lastLogIx entries <-+ atomically+ -- I don't know how much this is expected to happen, but in case+ -- multiple writes are queued up, we batch them into a group commit+ (flushTQueue writeQueue <&> NonEmpty.nonEmpty >>= maybe retry pure)+ <&> sconcat + void $ write entries+ atomically $ writeTQueue queue (EventLogPersisted t lastLogIx)+ handleEvent :: ( Ord node, MonadDelay m,@@ -221,14 +250,16 @@ handleEvent (EventRPCResult (CMR clusterMembershipResult)) = handleClusterMembershipResult clusterMembershipResult handleEvent (EventAdminRequest adminCommand) = handleAdminRequest adminCommand handleEvent (EventSnapshotPersisted snapshot) = applySnapshot snapshot+handleEvent (EventLogPersisted t ix) = whenRole Leader $ do+ ourTerm <- use term+ when (t == ourTerm) $ do+ durableIndex %= max ix+ applyLogEntries handleClientRequest :: ( Ord node, MonadMVar m,- MonadAsync m,- MonadMask m,- MonadFork m,- MonadDelay m+ MonadAsync m ) => NonEmpty (ClientRequest entry node) -> RaftT entry node result state m () handleClientRequest requests = do@@ -268,6 +299,8 @@ (appendLogEntries . fmap (\c -> (ourTerm, LogEntryCommand c))) (NonEmpty.nonEmpty $ NonEmpty.filter isNotReadOnly commands) + broadcastForPendingReads+ handleAppendEntries :: ( Ord node, MonadMVar m,@@ -315,6 +348,7 @@ aerNode = s, aerMatch = False, aerNewEntryLogIndex = ourLastIndex,+ aerPrevLogIndex = prevLogIndex, aerReadOnlySeqNum = leaderReadOnlySeqNum } )@@ -360,6 +394,7 @@ aerNode = s, aerMatch = True, aerNewEntryLogIndex = lastVerifiedIndex,+ aerPrevLogIndex = prevLogIndex, aerReadOnlySeqNum = leaderReadOnlySeqNum } )@@ -383,7 +418,7 @@ ) => AppendEntriesResult node result -> RaftT entry node result state m ()-handleAppendEntriesResult (AppendEntriesResult responderTerm responderNode responderSuccess responderLogIndex responderReadOnlySeqNum) = do+handleAppendEntriesResult (AppendEntriesResult responderTerm responderNode responderSuccess responderLogIndex responderPrevIndex responderReadOnlySeqNum) = do termComp <- handleTermNumber responderTerm ourRole <- use role when (ourRole == Leader && termComp == EQ) $@@ -403,28 +438,36 @@ %= Set.insert responderNode serveReadOnlyQueries+ broadcastForPendingReads applyLogEntries else do lastIx <- use commandLog <&> lastLogIndex -- Note that it's possible for a responder to not be known (we don't have its key- -- in `nextIndex`) due to in-flight cluster configuration changes. This is why+ -- in `followerProgress`) due to in-flight cluster configuration changes. This is why -- we have a fallback value (`fromMaybe`)- currentResponderIndex <- use (nextIndex . at responderNode) <&> fromMaybe (succ lastIx)+ follower <- use (followerProgress . at responderNode) <&> fromMaybe (newFollowerState (succ lastIx)) - let backedOff =- max- -- minimum valid log index is 0, so the minimum next index- -- must be `succ 0`- (succ 0)- ( min- (pred currentResponderIndex)- (succ responderLogIndex)- )- nextIndex . at responderNode .= Just backedOff- when (backedOff < currentResponderIndex) $- sendAppendEntriesTo responderNode+ -- The 'AppendEntries' RPC that led to this response may have been stale.+ -- If this is the case, we should ignore the result+ let isStale+ | follower ^. replicating = responderPrevIndex <= follower ^. matchIndex+ | otherwise = responderPrevIndex /= pred (follower ^. nextIndex) + unless isStale $ do+ let backedOff =+ max+ -- minimum valid log index is 0, so the minimum next index+ -- must be `succ 0`+ (succ 0)+ ( min+ responderPrevIndex+ (succ responderLogIndex)+ )+ followerProgress . at responderNode .= Just (follower & nextIndex .~ backedOff & replicating .~ False)+ when (backedOff < follower ^. nextIndex) $+ sendAppendEntriesTo responderNode+ -- | How to handle a term provided by another node. If this term -- is larger than ours, this means that we must clear some state from -- the previous term, and possibly transition to a new role.@@ -571,10 +614,7 @@ handleClusterMembershipRequest :: ( Ord node, MonadMVar m,- MonadAsync m,- MonadMask m,- MonadFork m,- MonadDelay m+ MonadAsync m ) => ClusterMembershipRequest node -> RaftT entry node result state m () handleClusterMembershipRequest request = do
src/Distributed/Consensus/Raft/Implementation.hs view
@@ -69,6 +69,22 @@ -- in the Cloud Haskell ecosystem. data Networking entry node result state m = Networking { -- | Send a remote procedure call to another Raft node.+ --+ -- The 'Networking' layer is responsible for some networking-specific logic.+ -- In particular, an 'InstallSnapshot' call is expected to carry a whole+ -- snapshot, which may be far too large to be carried by one message. Any+ -- chunking of 'InstallSnapshot' is expected to be done under the hood, since+ -- the chunking-specifics are intrinsically tied to the transport properties.+ --+ -- Concretely, if sending a whole 'Snapshot' is expensive in the transport,+ -- you will need to chunk the bytes of the serialized 'Snapshot', and send+ -- these chunks over separate messages. While a particular 'Snapshot' is+ -- being sent, any other call to 'sendRPC' for another 'Snapshot' should+ -- be a no-op, while calls for other message types in separate threads should+ -- go through.+ --+ -- Of course, 'receiveRPC' must also be able to reconstruct the 'InstallSnapshot'+ -- message, while being able to receive other messages in the meantime. sendRPC :: node -> RPC entry node state -> m (), -- | Send the result of a remote procedure call to another Raft node. sendRPCResult :: node -> RPCResult node result -> m (),@@ -229,6 +245,7 @@ aerNode :: !node, aerMatch :: !Bool, aerNewEntryLogIndex :: !LogIndex,+ aerPrevLogIndex :: !LogIndex, aerReadOnlySeqNum :: !ReadOnlySequenceNum } deriving (Eq, Ord, Show, Generic)@@ -315,6 +332,7 @@ | EventRPCResult (RPCResult node result) | EventAdminRequest (AdminRequest node) | EventSnapshotPersisted (Snapshot node state)+ | EventLogPersisted !Term !LogIndex deriving (Eq, Show) data EventContext node
src/Distributed/Consensus/Raft/Transformer.hs view
@@ -21,6 +21,8 @@ sendAdminResponse, whenRole, sendHeartbeat,+ broadcastAppendEntries,+ broadcastForPendingReads, sendAppendEntriesTo, setCommitIndex, voteFor,@@ -58,7 +60,7 @@ where import Control.Concurrent.Class.MonadMVar (MonadMVar, takeMVar)-import Control.Concurrent.Class.MonadSTM (atomically, readTQueue, writeTQueue)+import Control.Concurrent.Class.MonadSTM (atomically, check, isEmptyTQueue, readTQueue, writeTQueue) import Control.Monad (unless, void, when) import Control.Monad.Class.MonadAsync (MonadAsync, async, mapConcurrently_, race) import Control.Monad.Class.MonadFork (MonadFork)@@ -73,7 +75,7 @@ import Data.List.NonEmpty (NonEmpty) import qualified Data.List.NonEmpty as NonEmpty import qualified Data.Map.Strict as Map-import Data.Maybe (fromJust, isJust)+import Data.Maybe (fromJust, fromMaybe, isJust) import Data.Sequence (ViewR (..)) import qualified Data.Sequence as Seq import Data.Set (Set)@@ -102,14 +104,18 @@ import Lens.Micro.Platform ( assign, at,+ filtered, use, view, (%=),+ (%~), (+=), (.=),+ (.~), (^.), _1, _3,+ _Just, ) import System.Random (uniformR) @@ -196,19 +202,34 @@ sendHeartbeat = whenRole Leader $ do config <- view configuration- peers >>= traverse_ sendAppendEntriesTo+ broadcastAppendEntries view heartBeatTimer >>= lift . resetTimer config.heartBeatTimeout +broadcastAppendEntries :: (Ord node, MonadAsync m) => RaftT entry node result state m ()+broadcastAppendEntries = do+ peers >>= traverse_ sendAppendEntriesTo+ use readOnlySequenceNum >>= assign readOnlySeqBroadcast++-- | Check if we should broadcast an 'AppendEntries' RPC to service+-- pending reads. This can be used to trigger a heartbeat earlier+-- than the next regularly-scheduled heartbeat.+broadcastForPendingReads :: (Ord node, MonadAsync m) => RaftT entry node result state m ()+broadcastForPendingReads = whenRole Leader $ do+ broadcasted <- use readOnlySeqBroadcast+ latest <- use readOnlySequenceNum+ roundInFlight <- use pendingReadRequests <&> any ((<= broadcasted) . (^. pendingReadSequenceNum))+ when (latest > broadcasted && not roundInFlight) broadcastAppendEntries+ -- | For a given destination node, look up which of the entries -- in our log should be replicated, and send an appropriate 'AppendEntries' RPC. sendAppendEntriesTo :: (Ord node, MonadAsync m) => node -> RaftT entry node result state m () sendAppendEntriesTo destination = do entries <- use commandLog- use (nextIndex . at destination)+ use (followerProgress . at destination) >>= ( \case Nothing -> pure $ Just (0, initialTerm)- Just destNextIndex ->- let previousLogIndex = pred destNextIndex+ Just follower ->+ let previousLogIndex = pred (follower ^. nextIndex) in case entries Log.!? previousLogIndex of Found (!prevTerm, _, _) -> pure $ Just (previousLogIndex, prevTerm) NotFound -> pure $ Just (0, initialTerm)@@ -234,6 +255,16 @@ <*> use readOnlySequenceNum ) >>= runSend . sendRPC destination . AE++ -- Advanding 'nextIndex' optimistically is an excellent performance optimization.+ -- If the follower is known to be up-to-date ('replicating'), then we can assume+ -- it's still live.+ followerProgress+ . at destination+ . _Just+ . filtered (view replicating)+ . nextIndex+ .= succ (Log.lastLogIndex entries) Nothing -> ( InstallSnapshot <$> use term@@ -276,7 +307,8 @@ commitIndex' <- use commitIndex entries <- use commandLog ourTerm <- use term- matchIndices <- use matchIndex+ durable <- use durableIndex+ matchIndices <- use followerProgress <&> fmap (view matchIndex) s <- self clusterConf <- use clusterConfiguration @@ -286,7 +318,10 @@ -- -- All of this is done relative to the snapshot, hence why all of the -- indices are relativized- let relativeMatchIndices = fmap (Log.relativeIndex entries) matchIndices+ let -- Note that 'matchIndices' do not include the leader,+ -- so we take the leader into account by inserting it+ -- with the other match indices at its 'durableIndex'+ allMatchIndices = Map.insert s durable matchIndices relativeCommitIndex = Log.relativeIndex entries commitIndex' liveEntries = logEntries entries relativeQuorumIndices =@@ -311,9 +346,10 @@ -- Note that 'matchIndices' do not include the leader, -- so we take the leader into account by inserting it -- with the other match indices- ( Set.insert s $- Map.keysSet- (Map.filter (>= fromIntegral i) relativeMatchIndices)+ ( Map.keysSet+ -- using absolute indices here in case the match index is+ -- before the last snapshot+ (Map.filter (>= absoluteIndex entries (fromIntegral i)) allMatchIndices) ) ) & fmap fromIntegral@@ -448,10 +484,16 @@ (Ord node, Monad m) => node -> LogIndex -> RaftT entry node result state m () updateMatchIndex responder ackedIndex = do- prev <- use (matchIndex . at responder)- let newMatch = maybe ackedIndex (max ackedIndex) prev- matchIndex . at responder .= Just newMatch- nextIndex . at responder .= Just (succ newMatch)+ follower <- use (followerProgress . at responder) <&> fromMaybe (newFollowerState 0)+ let newMatch = max ackedIndex (follower ^. matchIndex)+ followerProgress+ . at responder+ .= Just+ ( follower+ & matchIndex .~ newMatch+ & nextIndex %~ max (succ newMatch)+ & replicating .~ True+ ) -- | Set up a callback for a client request acceptClientRequests ::@@ -628,16 +670,13 @@ appendLogEntries :: ( Ord node, MonadMVar m,- MonadAsync m,- MonadMask m,- MonadFork m,- MonadDelay m+ MonadAsync m ) => NonEmpty (Term, LogEntry entry node) -> RaftT entry node result state m () appendLogEntries entries = do- s <- self- impl <- view implementation+ writeQueue <- view persistenceQueue+ ourTerm <- use term startingLogIndex <- use commandLog <&> Log.lastLogIndex commandLog %= (`Log.extend` Seq.fromList (NonEmpty.toList entries)) @@ -646,7 +685,18 @@ (curry (\(ix, (t, entry)) -> (t, ix, entry))) [succ startingLogIndex ..] (NonEmpty.toList entries)- lift $ impl.persistence.writeLogEntry s batchToWrite++ lift $+ atomically $+ writeTQueue writeQueue $+ MkPersistenceBatch+ ourTerm+ ( startingLogIndex+ + fromIntegral+ (length entries)+ )+ batchToWrite+ for_ batchToWrite $ \(t, ix, entry) -> trace (\ctx -> LogEntryAppended ctx t ix entry) @@ -655,12 +705,7 @@ -- it's hard to check that the commit index is always <= the last log index use commandLog <&> Log.lastLogIndex >>= trace . flip LastLogIndexChangedTo - whenRole Leader $- peers >>= traverse_ sendAppendEntriesTo-- -- In a single-node cluster, we would already have- -- quorum to update our commit index- applyLogEntries+ whenRole Leader broadcastAppendEntries restoreState :: ( MonadMVar m,@@ -733,17 +778,13 @@ ps <- peers lastIx <- use commandLog <&> Log.lastLogIndex -- Pre-emptively prepare state for new membership- nextIndex %= \m -> Map.fromSet (\p -> Map.findWithDefault (succ lastIx) p m) ps- matchIndex %= (`Map.restrictKeys` ps)+ followerProgress %= \m -> Map.fromSet (\p -> Map.findWithDefault (newFollowerState (succ lastIx)) p m) ps unless (s `Set.member` allNodes clusterConf) becomeNonMember proposeClusterMembership :: ( MonadMVar m, MonadAsync m,- Ord node,- MonadMask m,- MonadFork m,- MonadDelay m+ Ord node ) => ClusterConfiguration node -> RaftT entry node result state m () proposeClusterMembership clusterConf = do@@ -753,7 +794,7 @@ -- | If the cluster is currently in a joint configuration, unify the -- membership to be in a simple configuration. Otherwise, do nothing.-unifyCluster :: (MonadMVar m, MonadAsync m, Ord node, MonadMask m, MonadFork m, MonadDelay m) => RaftT entry node result state m ()+unifyCluster :: (MonadMVar m, MonadAsync m, Ord node) => RaftT entry node result state m () unifyCluster = do pending <- pendingClusterMembershipChanges use clusterConfiguration >>= \case@@ -775,8 +816,10 @@ yesVotes .= Set.empty lastIx <- use commandLog <&> Log.lastLogIndex- peers <&> Map.fromSet (const (lastIx + 1)) >>= assign nextIndex+ peers <&> Map.fromSet (const (newFollowerState (lastIx + 1))) >>= assign followerProgress + durableIndex .= lastIx+ trace LeaderElected -- In order to serve read-only queries, there needs to be at least@@ -796,6 +839,10 @@ -- if the role isn't 'Leader' leaderStepDown :: (MonadAsync m) => Maybe node -> RaftT entry node result state m () leaderStepDown mNewLeader = whenRole Leader $ do+ -- Wait for writes to complete+ persistQueue <- view persistenceQueue+ lift $ atomically $ isEmptyTQueue persistQueue >>= check+ clientReqs <- use currentClientRequests for_ (Map.toList clientReqs) $ \(reqId, requester) -> do runSend $ sendClientResponse requester (MkResponse reqId mNewLeader NotLeader)@@ -845,8 +892,7 @@ currentLeader .= Nothing -- The following pieces of state are only useful to leaders- nextIndex .= mempty- matchIndex .= mempty+ followerProgress .= mempty s <- self term += 1
src/Distributed/Consensus/Raft/Transformer/Definition.hs view
@@ -11,10 +11,14 @@ implementation, configuration, eventQueue,+ persistenceQueue, heartBeatTimer, electionTimer, exitLock, + -- ** Persistence batching+ PersistenceBatch (..),+ -- ** Read-only operations RaftSendT, runSend,@@ -32,16 +36,24 @@ commandLog, commitIndex, lastApplied,- nextIndex,- matchIndex,+ followerProgress,+ durableIndex, pendingConfigurationIndex, yesVotes, currentClientRequests, pendingReadRequests, readOnlySequenceNum,+ readOnlySeqBroadcast, snapshotInProgress, randomGen, + -- ** Follower state+ FollowerState,+ newFollowerState,+ nextIndex,+ matchIndex,+ replicating,+ -- ** Read-only client requests PendingRead (..), pendingReadTerm,@@ -64,7 +76,7 @@ where import Control.Concurrent.Class.MonadMVar (MVar, MonadMVar, newEmptyMVar)-import Control.Concurrent.Class.MonadSTM (TQueue, atomically, newTQueue, writeTQueue)+import Control.Concurrent.Class.MonadSTM (TQueue, atomically, newTQueueIO, writeTQueue) import Control.Monad (void) import Control.Monad.Class.MonadAsync (MonadAsync, async) import Control.Monad.Class.MonadSTM (MonadSTM)@@ -119,6 +131,19 @@ -- in which case this cluster has a single node InCluster (Set node) +data FollowerState+ = MkFollowerState+ { _nextIndex :: !LogIndex,+ _matchIndex :: !LogIndex,+ -- | Whether the follower has acked at least an 'AppendEntries' in this term.+ -- If this is the case, then we can assume that the follower is live and+ -- advance 'nextIndex' optimistically.+ _replicating :: !Bool+ }++newFollowerState :: LogIndex -> FollowerState+newFollowerState next = MkFollowerState next 0 False+ data RaftState entry node result state = MkRaftState { _role :: !Role, _term :: !Term,@@ -129,8 +154,12 @@ _commandLog :: !(Log (LogEntry entry node) node), _commitIndex :: !LogIndex, _lastApplied :: !LogIndex,- _nextIndex :: !(Map node LogIndex),- _matchIndex :: !(Map node LogIndex),+ _followerProgress :: !(Map node FollowerState),+ -- | Highest log index known to be persisted by this node as the leader.+ -- Only entries up to this index count the leader towards their quorum.+ --+ -- Tracking this allows to persist entries to disk concurrently.+ _durableIndex :: !LogIndex, -- | Until this log index has been applied, a cluster configuration -- change should not be started, possibly because another cluster -- configuration change is ongoing.@@ -143,6 +172,9 @@ -- when a heartbeat counts to acknowledge a read-only request (or was already -- in-flight, for example) _readOnlySequenceNum :: !ReadOnlySequenceNum,+ -- | Value of '_readOnlySequenceNum' when an 'AppendEntries' RPC or heartbeat was last+ -- broadcast.+ _readOnlySeqBroadcast :: !ReadOnlySequenceNum, -- | 'True' if a snapshot is currently being written to storage, which is done asynchronously. _snapshotInProgress :: !Bool, _randomGen :: !StdGen@@ -186,18 +218,33 @@ _commandLog = newLog, _commitIndex = 0, _lastApplied = 0,- _nextIndex = mempty,- _matchIndex = mempty,+ _followerProgress = mempty,+ _durableIndex = 0, _pendingConfigurationIndex = 0, _yesVotes = mempty, _currentClientRequests = mempty, _pendingReadRequests = mempty, _readOnlySequenceNum = 0,+ _readOnlySeqBroadcast = 0, -- We use mkStdGen64 for reproducibility across 32-bit and 64-bit architectures _snapshotInProgress = False, _randomGen = mkStdGen64 seed } +-- | Represents a batch of entries to persist,+-- including metadata necessary to update the state+-- once the write has completed+data PersistenceBatch entry node+ = MkPersistenceBatch+ { pbTerm :: !Term,+ pbEdgeLogIndex :: !LogIndex,+ pbEntries :: ![(Term, LogIndex, LogEntry entry node)]+ }++instance Semigroup (PersistenceBatch entry node) where+ (MkPersistenceBatch _ _ e1) <> MkPersistenceBatch t2 l2 e2 =+ MkPersistenceBatch t2 l2 (e1 <> e2)+ runRaftT :: ( Ord node, MonadSTM m,@@ -210,7 +257,8 @@ RaftT entry node result state m a -> m a runRaftT config startingState internalState impl f = do- queue <- atomically newTQueue+ queue <- newTQueueIO+ persistQueue <- newTQueueIO hbTimer <- newTimer (atomically $ writeTQueue queue EventHeartBeatTimeout) elTimer <- newTimer (atomically $ writeTQueue queue EventElectionTimeout) exitLock <- newEmptyMVar@@ -224,6 +272,7 @@ { _configuration = config, _implementation = impl, _eventQueue = queue,+ _persistenceQueue = persistQueue, _heartBeatTimer = hbTimer, _electionTimer = elTimer, _exitLock = exitLock@@ -236,6 +285,7 @@ { _configuration :: !(Config node), _implementation :: !(Implementation entry node result state m), _eventQueue :: TQueue m (Event entry node result state),+ _persistenceQueue :: TQueue m (PersistenceBatch entry node), -- Handle to a thread which will send a heartbeat timeout -- event after the appropriate amount of time. _heartBeatTimer :: Timer m,@@ -293,4 +343,5 @@ makeLenses ''RaftEnv makeLenses ''RaftState+makeLenses ''FollowerState makeLenses ''PendingRead