packages feed

linearizable (empty) → 0.1.0.0

raw patch · 7 files changed

+452/−0 lines, 7 filesdep +basedep +containersdep +linearizable

Dependencies added: base, containers, linearizable, tasty, tasty-hunit

Files

+ CHANGELOG.md view
@@ -0,0 +1,5 @@+# Revision history for linearizability++## 0.1.0.0 -- YYYY-mm-dd++* First version. Released on an unsuspecting world.
+ LICENSE view
@@ -0,0 +1,29 @@+Copyright (c) 2026, Laurent P. René de Cotret+++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++    * Redistributions of source code must retain the above copyright+      notice, this list of conditions and the following disclaimer.++    * Redistributions in binary form must reproduce the above+      copyright notice, this list of conditions and the following+      disclaimer in the documentation and/or other materials provided+      with the distribution.++    * Neither the name of the copyright holder nor the names of its+      contributors may be used to endorse or promote products derived+      from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,10 @@+# linearizable++Simple linearizability checker based on++>  M. P. Herlihy and J. M. Wing, "Linearizability: a correctness condition for concurrent objects",+>    ACM Transactions on Programming Languages and Systems. Volume 12, issue 3, pages 463 - 492.+    +as vulgarized by Guanzhou Hu (https://www.josehu.com/technical/2024/07/28/on-line-linearizability-checker.html)++See the module documentation for a guide on how to use this package.
+ linearizable.cabal view
@@ -0,0 +1,50 @@+cabal-version:      3.4+name:               linearizable+version:            0.1.0.0+synopsis:           Linearizability checker+description:        Linearizability checker for experimental event histories. This is useful for testing+                    the properties of a distributed system given, for example.+homepage:           https://github.com/LaurentRDC/distributed-consensus+license:            BSD-3-Clause+license-file:       LICENSE+author:             Laurent P. René de Cotret+maintainer:         laurent.decotret@outlook.com+copyright:          Laurent P. René de Cotret+category:           Distributed Systems+build-type:         Simple+extra-doc-files:    CHANGELOG.md+                    README.md++-- extra-source-files:++common warnings+    ghc-options: -Wall+                 -Wcompat+                 -Widentities+                 -Wincomplete-uni-patterns+                 -Wincomplete-record-updates+                 -Wredundant-constraints+                 -fhide-source-paths+                 -Wpartial-fields+                 -Wunused-packages++library+    import:           warnings+    exposed-modules:  Control.Concurrent.Linearizable+    build-depends:    base >= 4.18 && <4.23+                    , containers >=0.7 && <0.9+    hs-source-dirs:   src+    default-language: Haskell2010++test-suite linearizable-test+    import:           warnings+    default-language: Haskell2010+    ghc-options:      -rtsopts -threaded "-with-rtsopts=-N"+    type:             exitcode-stdio-1.0+    hs-source-dirs:   tests+    main-is:          Main.hs+    other-modules:    Test.Control.Concurrent.Linearizable+    build-depends:    base+                    , tasty ^>=1.5+                    , tasty-hunit ^>=0.10+                    , linearizable
+ src/Control/Concurrent/Linearizable.hs view
@@ -0,0 +1,217 @@+-----------------------------------------------------------------------------++-- |+-- Module:      $module+-- Copyright:   (c) Laurent P. René de Cotret+-- License:     BSD 3-Clause+--+-- Simple linearizability checker based on+--+--   * M. P. Herlihy and J. M. Wing, \"/Linearizability: a correctness condition for concurrent objects/\",+--     ACM Transactions on Programming Languages and Systems. Volume 12, issue 3, pages 463 - 492.+--+-- as <https://www.josehu.com/technical/2024/07/28/on-line-linearizability-checker.html vulgarized by Guanzhou Hu>.+--+-- === How to use this module+--+-- The only useful function here is 'linearizable'. The idea is that 'linearizable' checks+-- whether it is /possible/ that the events fed to it were ever part of a linear history.+module Control.Concurrent.Linearizable+  ( linearizable,++    -- * Modeling+    Model (..),+    Event (..),+  )+where++import Data.Foldable (foldlM)+import Data.List (sortOn)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (mapMaybe)+import Data.Sequence (Seq, ViewL ((:<)), (|>))+import qualified Data.Sequence as Seq+import Data.Set (Set)+import qualified Data.Set as Set++-- | Experimental event. Note that, typically, the @operation@ type+-- parameter tracks both what was the input to the state machine,+-- as well as what was the result of the input.+data Event timestamp operation+  = MkEvent+  { timestampReq :: timestamp,+    timestampAck :: timestamp,+    operation :: operation+  }+  deriving (Show, Eq, Ord)++-- | Model for a state machine.+--+-- Consider a state machine that is a single counter. The 'Model' would be:+--+-- @+-- data Command+--     = Increment+--     | Decrement+--+-- model :: Model Int (Command, Int)+-- model = Model+--       { initialState = 0+--       , apply = \\(op, result) value ->+--                   let expectedState = case op of+--                          Increment = succ value+--                          Decrement = pred value+--                   in if result == expectation+--                          then Just expectation+--                          else Nothing+--       }+-- @+--+-- Here, the @operation@ type parameter represents both what the input+-- was (here, @Command@), as well as what the experimental result of that+-- command was (here, @Int@, the new state of the counter).+--+-- In particular, note how the model returns @'Nothing'@ in case the state is+-- inconsistent with the experimental history.+data Model state operation+  = MkModel+  { initialState :: state,+    apply :: operation -> state -> Maybe state+  }++data Possibility node state timestamp operation+  = MkPossibility+  { state :: state,+    queues :: Map node (Seq (Event timestamp operation))+  }+  deriving (Eq, Ord)++data Checker node state timestamp operation+  = MkChecker+  { model :: Model state operation,+    possibilities :: Set (Possibility node state timestamp operation)+  }++-- | Check a model for a state machine against an experimental+-- history of events. Events will be sorted appropriately before+-- linearizability is checked.+--+-- Returns 'True' if it's possible to place events in linear order+-- that is accepted by the 'Model'.+--+-- Note that checking linearizbility is NP-complete; this means that+-- 'linearizable' may take a long time, and/or require lots of resources.+-- If you can, try to break down the 'Model' into individual components.+-- For example, if you were testing the linearizability of operations+-- on a key-value store, you might want to check the+-- linearizability of events related to each key individually.+linearizable ::+  ( Ord node,+    Ord state,+    Ord timestamp,+    Ord operation+  ) =>+  Model state operation ->+  -- | Experimental history. The order of events need not be sorted in advance.+  [(node, Event timestamp operation)] ->+  Bool+linearizable _ [] = True+linearizable m events =+  maybe+    False+    (any (canDrain m) . possibilities)+    (foldlM feed (checker nodes) (zip sortedEvents stillActive))+  where+    nodes = foldMap (Set.singleton . fst) events++    sortedEvents = sortOn (timestampAck . snd) events+    -- stillActive !! i is the set of nodes that have at least one event+    -- /after/ the i-th event, i.e. the nodes we must still wait for+    stillActive = drop 1 (scanr (Set.insert . fst) Set.empty sortedEvents)++    checker ns =+      MkChecker m $+        Set.singleton+          MkPossibility+            { state = initialState m,+              queues =+                Map.fromList+                  [ (n, mempty)+                  | n <- Set.toList ns+                  ]+            }++feed ::+  (Ord node, Ord state, Ord timestamp, Ord operation) =>+  Checker node state timestamp operation ->+  ((node, Event timestamp operation), Set node) ->+  Maybe (Checker node state timestamp operation)+feed c ((node, event), active)+  | Set.null newPossibilities = Nothing+  | otherwise = Just c {possibilities = newPossibilities}+  where+    newPossibilities =+      let enqueue p = p {queues = Map.adjust (|> event) node (queues p)}+       in stepAll active (model c) (Set.map enqueue (possibilities c))++stepAll ::+  (Ord state, Ord node, Ord timestamp, Ord operation) =>+  -- | Nodes that may still produce events+  Set node ->+  Model state operation ->+  Set (Possibility node state timestamp operation) ->+  Set (Possibility node state timestamp operation)+stepAll active m ps+  | Set.null ready = ps+  | otherwise = stepAll active m (rest `Set.union` Set.fromList (concatMap (successors m) (Set.toList ready)))+  where+    (ready, rest) = Set.partition steppable ps++    steppable p =+      not (all null (queues p))+        && and [not (null q) | (n, q) <- Map.toList (queues p), n `Set.member` active]++successors ::+  (Ord node, Ord timestamp) =>+  Model state operation ->+  Possibility node state timestamp operation ->+  [Possibility node state timestamp operation]+successors m p+  | Map.null heads = []+  | otherwise = mapMaybe step (Map.toList heads)+  where+    safeHead xs = case Seq.viewl xs of+      Seq.EmptyL -> Nothing+      (x :< _) -> Just x++    heads = Map.mapMaybe safeHead (queues p)++    minAck = minimum (timestampAck <$> heads)++    step (n, h)+      | timestampReq h < minAck = do+          v <- apply m (operation h) (state p)+          pure $ p {state = v, queues = Map.adjust (Seq.drop 1) n (queues p)}+      | otherwise = Nothing++-- | Once the whole history has been read, search depth-first for /one/ way+-- to linearize all of the remaining events.+canDrain ::+  (Ord node, Ord state, Ord timestamp) =>+  Model state operation ->+  Possibility node state timestamp operation ->+  Bool+canDrain m p0 = fst (go Set.empty p0)+  where+    key p = (state p, Seq.length <$> Map.elems (queues p))++    go seen p+      | all null (queues p) = (True, seen)+      | key p `Set.member` seen = (False, seen)+      | otherwise = firstSuccess (Set.insert (key p) seen) (successors m p)++    firstSuccess seen [] = (False, seen)+    firstSuccess seen (q : qs) = case go seen q of+      (True, seen') -> (True, seen')+      (False, seen') -> firstSuccess seen' qs
+ tests/Main.hs view
@@ -0,0 +1,8 @@+module Main (main) where++import Test.Control.Concurrent.Linearizable (tests)+import Test.Tasty (defaultMain)++main :: IO ()+main =+  defaultMain tests
+ tests/Test/Control/Concurrent/Linearizable.hs view
@@ -0,0 +1,133 @@+{-# LANGUAGE TypeApplications #-}++module Test.Control.Concurrent.Linearizable (tests) where++import Control.Concurrent.Linearizable (Event (..), Model (..), linearizable)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, testCase)++tests :: TestTree+tests =+  testGroup+    "Control.Concurrent.Linearizable"+    [ testEmptyHistoryLinearizable,+      testLinearizableExample,+      testNonLinearizableExample,+      testLinearizableExampleWithFail,+      testIdleNode,+      testIdleNodeNonLinearizable,+      testEarlyFinisher+    ]++testEmptyHistoryLinearizable :: TestTree+testEmptyHistoryLinearizable =+  testCase "Empty example" $+    let emptyHistory = [] :: [(Int, Event Timestamp Op)]+     in assertBool+          "Trivial history should be linearizable"+          (linearizable model emptyHistory)++testLinearizableExample :: TestTree+testLinearizableExample = testCase "Linearizable example" $ do+  let history =+        [ (2, get Nothing 99 101),+          (0, put 8 100 105),+          (1, put 7 104 106),+          (2, get (Just 7) 102 108),+          (1, get (Just 8) 110 112),+          (2, get (Just 9) 109 115),+          (0, get (Just 8) 111 117),+          (1, put 9 114 118)+        ]+  assertBool "History should be linearizable" (linearizable @Int model history)++testNonLinearizableExample :: TestTree+testNonLinearizableExample = testCase "Non-linearizable example" $ do+  let history =+        [ (0, put 8 100 105),+          (1, put 7 104 106),+          (2, put 9 107 110),+          (0, get (Just 7) 111 113)+        ]+  assertBool "History should not be linearizable" (not $ linearizable @Int model history)++testLinearizableExampleWithFail :: TestTree+testLinearizableExampleWithFail = testCase "Linearizable example with failures" $ do+  let history =+        [ (0, put 8 100 105),+          (1, failed 104 107),+          (1, get (Just 8) 109 110),+          (0, get (Just 7) 111 112),+          (1, get (Just 9) 113 114),+          (1, put 10 115 117),+          (0, get (Just 10) 118 119)+        ]+  assertBool "History should be linearizable" (linearizable @Int model history)++testIdleNode :: TestTree+testIdleNode = testCase "Idle node in the node list" $ do+  -- node 2 isn't involved in the history+  let history =+        [ (0, put 1 0 2),+          (1, get (Just 1) 3 4),+          (0, put 2 5 6),+          (1, get (Just 2) 7 8)+        ]+  assertBool "History should be linearizable" (linearizable @Int model history)++testIdleNodeNonLinearizable :: TestTree+testIdleNodeNonLinearizable = testCase "Idle node, non-linearizable history" $ do+  -- node 2 isn't involved in the history, but also the history+  -- isn't linearizable+  let history =+        [ (0, put 1 0 2),+          (1, get (Just 2) 3 4)+        ]+  assertBool "History should not be linearizable" (not $ linearizable @Int model history)++testEarlyFinisher :: TestTree+testEarlyFinisher = testCase "Client finishing early" $ do+  -- node 0's history ends early+  let history =+        [ (0, put 0 0 1),+          (1, get (Just 0) 2 3),+          (2, put 5 4 5),+          (1, get (Just 5) 6 7),+          (2, get (Just 5) 8 9)+        ]+  assertBool "History should be linearizable" (linearizable @Int model history)++data State+  = Unknown+  | Known (Maybe Int)+  deriving (Eq, Ord)++model :: Model State Op+model =+  MkModel+    { initialState = Known Nothing,+      apply = \op s -> case op of+        Put x -> pure (Known (Just x))+        Get expectation+          | s == Unknown -> pure s+          | s == Known expectation -> pure s+          | otherwise -> Nothing+        Failed -> pure Unknown+    }++type Timestamp = Int++get :: Maybe Int -> Timestamp -> Timestamp -> Event Timestamp Op+get expectation req ack = MkEvent req ack (Get expectation)++put :: Int -> Timestamp -> Timestamp -> Event Timestamp Op+put value req ack = MkEvent req ack (Put value)++failed :: Timestamp -> Timestamp -> Event Timestamp Op+failed req ack = MkEvent req ack Failed++data Op+  = Put Int+  | Get (Maybe Int) -- expected result+  | Failed -- value uncertain+  deriving (Eq, Ord, Show)