{-# LANGUAGE DataKinds #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedRecordDot #-}

-- | Tests of the LeiosFetch decision logic, on scenarios built directly from
-- its outstanding state and the peers' offers.
module Test.Consensus.Leios.LeiosFetch.Decision (tests) where

import Cardano.Crypto.Hash (Hash (UnsafeHash))
import Cardano.Ledger.Keys (KeyHash (..))
import Cardano.Slotting.Slot (SlotNo (..), WithOrigin (..))
import qualified Data.ByteString.Short as SBS
import Data.Foldable (toList)
import qualified Data.Foldable as F
import Data.Function ((&))
import qualified Data.IntMap.NonEmpty as NEIntMap
import qualified Data.IntMap.Strict as IntMap
import qualified Data.IntSet as IntSet
import qualified Data.IntSet.NonEmpty as NEIntSet
import qualified Data.Map.NonEmpty as NEMap
import qualified Data.Map.Strict as Map
import Data.Maybe.Strict (StrictMaybe (SNothing))
import Data.Sequence.NonEmpty (NESeq)
import qualified Data.Set as Set
import qualified Data.Set.NonEmpty as NESet
import Data.Word (Word64)
import Ouroboros.Consensus.Forecast (OutsideForecastRange (..))
import Ouroboros.Consensus.Leios.Types
  ( BytesSize
  , ElectionId (..)
  , EndorserBlockHash
  , LeiosEbByteSizes (..)
  , LeiosPoint (..)
  , SizeRole (..)
  , TxHash
  , idLeiosEbByteSizesLimit
  )
import Ouroboros.Consensus.MiniProtocol.LeiosFetch.Decision
  ( EbFetchState (..)
  , EbState (..)
  , LeiosBlockRequest (..)
  , LeiosBlockTxsRequest (..)
  , LeiosFetchRequest (..)
  , LeiosFetchStaticEnv (..)
  , LeiosOutstanding (..)
  , OfferedHalves (..)
  , PeerOffer (MkPeerOffer)
  , acquireEbBody
  , completeTxRequest
  , defaultLeiosFetchStaticEnv
  , emptyLeiosOutstanding
  , fetchPriorityTiers
  , focusCertifiedEb
  , focusElectionIfUnfocused
  , holdForgedEb
  , leiosFetchLogicIteration
  , newLeiosJobPool
  , peerBudget
  , pruneOffers
  , pruneOutstandingToImmTip
  , recordReferencedPoint
  , refundEbRequest
  , refundTxRequest
  , removePeerFromOutstanding
  )
import qualified Ouroboros.Consensus.MiniProtocol.LeiosFetch.Jobs as Jobs
import Ouroboros.Network.PeerSelection.LedgerPeers.Type (IsBigLedgerPeer (..))
import System.Random (mkStdGen)
import Test.QuickCheck
  ( Gen
  , Property
  , arbitrary
  , choose
  , counterexample
  , forAll
  , frequency
  , property
  , sublistOf
  , tabulate
  , vectorOf
  )
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))
import Test.Tasty.QuickCheck (testProperty)

tests :: TestTree
tests :: TestTree
tests =
  String -> [TestTree] -> TestTree
testGroup
    String
"decision"
    [ String -> [TestTree] -> TestTree
testGroup
        String
"EB body fetch"
        [ String -> Assertion -> TestTree
testCase String
"single missing body with one offering peer issues one request" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
            Assertion
test_singleMissingBody
        , String -> Assertion -> TestTree
testCase String
"no request when no peer offers the body" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
            Assertion
test_bodyNoOffer
        , String -> Assertion -> TestTree
testCase String
"a peer already asked for a body is not asked again" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
            Assertion
test_bodyAlreadyRequestedPeerSkipped
        , String -> Assertion -> TestTree
testCase String
"both offering peers are selected (no per-EB cap)" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
            Assertion
test_bodyTwoPeersOffer
        , String -> Assertion -> TestTree
testCase
            String
"a peer offering the body and the closure is asked for the body once, even after its reply"
            Assertion
test_bodyAskedOnceOfBothOfferer
        , String -> Assertion -> TestTree
testCase
            String
"a closure offered while the decision is pruning a body offer is still asked of the peer"
            Assertion
test_closureOfferedMeanwhile
        , String -> Assertion -> TestTree
testCase
            String
"nothing of an endorser block the node's own forge produced is asked of a peer offering it"
            Assertion
test_forgedNotFetched
        , String -> Assertion -> TestTree
testCase
            String
"an endorser block rejected as too big at a point is never fetched again at that point"
            Assertion
test_noRefetchOversized
        , String -> Assertion -> TestTree
testCase
            String
"a body offered beyond the forecast range is kept, and requested once a forecast reaches it"
            Assertion
test_bodyBeyondForecastKept
        , String -> Assertion -> TestTree
testCase String
"per-peer byte budget exhausted skips that peer" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
            Assertion
test_perPeerByteBudget
        , String -> Assertion -> TestTree
testCase
            String
"a body that does not fit a peer's remaining budget is not requested, nor is any offer after it"
            Assertion
test_perPeerByteBudgetHard
        ]
    , String -> [TestTree] -> TestTree
testGroup
        String
"EB closure fetch"
        [ String -> Assertion -> TestTree
testCase String
"a big-ledger peer has a larger, but still finite, closure budget" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
            Assertion
test_bigLedgerPeerBudget
        , String -> Assertion -> TestTree
testCase
            String
"job assignment draws within the least-requested bucket, at random, respecting exclusions"
            Assertion
test_pickJobs
        ]
    , String -> [TestTree] -> TestTree
testGroup
        String
"focus"
        [ String -> Assertion -> TestTree
testCase String
"a verified certificate for an election older than the pruned slot changes nothing" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
            Assertion
test_focusCertifiedPruned
        , String -> Assertion -> TestTree
testCase
            String
"a verified certificate moves its election onto an endorser block that lost the announcement race"
            Assertion
test_focusCertifiedEb
        ]
    , String -> [TestTree] -> TestTree
testGroup
        String
"bookkeeping"
        [ String -> Property -> TestTree
forall a. Testable a => String -> a -> TestTree
testProperty
            String
"the outstanding state agrees with the requests in flight, whatever settles them"
            Property
prop_bookkeeping
        ]
    , String -> [TestTree] -> TestTree
testGroup
        String
"fetch priority"
        [ String -> Assertion -> TestTree
testCase String
"freshest window oldest-first, then rest freshest-first" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
            Assertion
test_fetchPriorityOrder
        ]
    ]

-- | With current slot S=100 and window L=10, EBs at slot >= 90 (the voting
-- window) are prioritised oldest-first, EBs beyond S trail that first tier, and
-- everything older is freshest-first.
test_fetchPriorityOrder :: IO ()
test_fetchPriorityOrder :: Assertion
test_fetchPriorityOrder =
  (LeiosPoint -> Word64) -> [LeiosPoint] -> [Word64]
forall a b. (a -> b) -> [a] -> [b]
map (SlotNo -> Word64
unSlot (SlotNo -> Word64)
-> (LeiosPoint -> SlotNo) -> LeiosPoint -> Word64
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (.pointSlotNo)) ([LeiosPoint]
hi [LeiosPoint] -> [LeiosPoint] -> [LeiosPoint]
forall a. [a] -> [a] -> [a]
++ [LeiosPoint]
lo)
    [Word64] -> [Word64] -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= [Word64
90, Word64
95, Word64
100, Word64
101, Word64
105, Word64
89, Word64
50, Word64
0]
 where
  ([LeiosPoint]
hi, [LeiosPoint]
lo) = Maybe (SlotNo, Word64)
-> [(SlotNo, LeiosPoint)] -> ([LeiosPoint], [LeiosPoint])
forall v. Maybe (SlotNo, Word64) -> [(SlotNo, v)] -> ([v], [v])
fetchPriorityTiers ((SlotNo, Word64) -> Maybe (SlotNo, Word64)
forall a. a -> Maybe a
Just (Word64 -> SlotNo
SlotNo Word64
100, Word64
10)) [(SlotNo, LeiosPoint)]
offers
  offers :: [(SlotNo, LeiosPoint)]
offers = [(Word64 -> SlotNo
SlotNo (Word -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word
a), Word -> Char -> LeiosPoint
point Word
a Char
'x') | Word
a <- [Word
0, Word
105, Word
90, Word
50, Word
100, Word
89, Word
101, Word
95]]
  unSlot :: SlotNo -> Word64
unSlot (SlotNo Word64
n) = Word64
n

{-------------------------------------------------------------------------------
  Scenarios
-------------------------------------------------------------------------------}

-- | Peers are just numbers here.
type Peer = Int

peerA, peerB :: Peer
peerA :: Int
peerA = Int
0
peerB :: Int
peerB = Int
1

test_singleMissingBody :: IO ()
test_singleMissingBody :: Assertion
test_singleMissingBody =
  Scenario
empty
    Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& LeiosPoint -> Word32 -> Scenario -> Scenario
withMissingBody (Word -> Char -> LeiosPoint
point Word
1 Char
'a') Word32
1024
    Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& Int -> [LeiosPoint] -> Scenario -> Scenario
offersBody Int
peerA [Word -> Char -> LeiosPoint
point Word
1 Char
'a']
    Scenario
-> (Scenario -> Map Int (NESeq LeiosFetchRequest))
-> Map Int (NESeq LeiosFetchRequest)
forall a b. a -> (a -> b) -> b
& Scenario -> Map Int (NESeq LeiosFetchRequest)
runIteration
    Map Int (NESeq LeiosFetchRequest)
-> (Map Int (NESeq LeiosFetchRequest) -> Assertion) -> Assertion
forall a b. a -> (a -> b) -> b
& Int
-> LeiosPoint
-> Word32
-> Map Int (NESeq LeiosFetchRequest)
-> Assertion
assertBodyRequest Int
peerA (Word -> Char -> LeiosPoint
point Word
1 Char
'a') Word32
1024

test_bodyNoOffer :: IO ()
test_bodyNoOffer :: Assertion
test_bodyNoOffer =
  Scenario
empty
    Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& LeiosPoint -> Word32 -> Scenario -> Scenario
withMissingBody (Word -> Char -> LeiosPoint
point Word
1 Char
'a') Word32
1024
    Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& Int -> [LeiosPoint] -> Scenario -> Scenario
offersBody Int
peerA [Word -> Char -> LeiosPoint
point Word
1 Char
'b'] -- peer offers a different EB, not the one we need
    Scenario
-> (Scenario -> Map Int (NESeq LeiosFetchRequest))
-> Map Int (NESeq LeiosFetchRequest)
forall a b. a -> (a -> b) -> b
& Scenario -> Map Int (NESeq LeiosFetchRequest)
runIteration
    Map Int (NESeq LeiosFetchRequest)
-> (Map Int (NESeq LeiosFetchRequest) -> Assertion) -> Assertion
forall a b. a -> (a -> b) -> b
& Map Int (NESeq LeiosFetchRequest) -> Assertion
assertNoRequests

test_bodyAlreadyRequestedPeerSkipped :: IO ()
test_bodyAlreadyRequestedPeerSkipped :: Assertion
test_bodyAlreadyRequestedPeerSkipped =
  Scenario
empty
    Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& LeiosPoint -> Word32 -> Scenario -> Scenario
withMissingBody (Word -> Char -> LeiosPoint
point Word
1 Char
'a') Word32
1024
    Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& LeiosPoint -> [Int] -> Scenario -> Scenario
alreadyRequestedEbFrom (Word -> Char -> LeiosPoint
point Word
1 Char
'a') [Int
peerA] -- already in flight from peerA
    Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& Int -> [LeiosPoint] -> Scenario -> Scenario
offersBody Int
peerA [Word -> Char -> LeiosPoint
point Word
1 Char
'a'] -- so peerA is not asked again
    Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& Int -> [LeiosPoint] -> Scenario -> Scenario
offersBody Int
peerB [Word -> Char -> LeiosPoint
point Word
1 Char
'a'] -- but a fresh offering peer is
    Scenario
-> (Scenario -> Map Int (NESeq LeiosFetchRequest))
-> Map Int (NESeq LeiosFetchRequest)
forall a b. a -> (a -> b) -> b
& Scenario -> Map Int (NESeq LeiosFetchRequest)
runIteration
    Map Int (NESeq LeiosFetchRequest)
-> (Map Int (NESeq LeiosFetchRequest) -> Assertion) -> Assertion
forall a b. a -> (a -> b) -> b
& [Int] -> Map Int (NESeq LeiosFetchRequest) -> Assertion
assertRequestPeers [Int
peerB]

test_bodyTwoPeersOffer :: IO ()
test_bodyTwoPeersOffer :: Assertion
test_bodyTwoPeersOffer =
  Scenario
empty
    Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& LeiosPoint -> Word32 -> Scenario -> Scenario
withMissingBody (Word -> Char -> LeiosPoint
point Word
1 Char
'a') Word32
1024
    Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& Int -> [LeiosPoint] -> Scenario -> Scenario
offersBody Int
peerA [Word -> Char -> LeiosPoint
point Word
1 Char
'a']
    Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& Int -> [LeiosPoint] -> Scenario -> Scenario
offersBody Int
peerB [Word -> Char -> LeiosPoint
point Word
1 Char
'a']
    Scenario
-> (Scenario -> Map Int (NESeq LeiosFetchRequest))
-> Map Int (NESeq LeiosFetchRequest)
forall a b. a -> (a -> b) -> b
& Scenario -> Map Int (NESeq LeiosFetchRequest)
runIteration
    -- both peers offer; with no per-EB cap the body is requested from both
    Map Int (NESeq LeiosFetchRequest)
-> (Map Int (NESeq LeiosFetchRequest) -> Assertion) -> Assertion
forall a b. a -> (a -> b) -> b
& Int -> Map Int (NESeq LeiosFetchRequest) -> Assertion
assertRequestPeerCount Int
2

-- | A peer that offers both the body and the closure is asked for the body, and
-- not again once its reply has arrived but before the body is held. Its
-- closure is still asked of it once the body is held.
test_bodyAskedOnceOfBothOfferer :: IO ()
test_bodyAskedOnceOfBothOfferer :: Assertion
test_bodyAskedOnceOfBothOfferer = do
  Int
-> LeiosPoint
-> Word32
-> Map Int (NESeq LeiosFetchRequest)
-> Assertion
assertBodyRequest Int
peerA LeiosPoint
p Word32
1024 Map Int (NESeq LeiosFetchRequest)
reqs1
  Map Int (NESeq LeiosFetchRequest) -> Assertion
assertNoRequests Map Int (NESeq LeiosFetchRequest)
reqs2
  Map Int (NESeq LeiosFetchRequest) -> IntSet
requestedOffsets Map Int (NESeq LeiosFetchRequest)
reqs3 IntSet -> IntSet -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Int -> IntSet
IntSet.singleton Int
0
 where
  p :: LeiosPoint
p = Word -> Char -> LeiosPoint
point Word
1 Char
'a'
  offers0 :: Map LeiosPoint PeerOffer
offers0 = LeiosPoint -> PeerOffer -> Map LeiosPoint PeerOffer
forall k a. k -> a -> Map k a
Map.singleton LeiosPoint
p (StrictMaybe (LeiosEbByteSizes 'SizeLimit)
-> OfferedHalves -> PeerOffer
MkPeerOffer StrictMaybe (LeiosEbByteSizes 'SizeLimit)
forall a. StrictMaybe a
SNothing (Word32 -> OfferedHalves
OfferedBodyAndClosure Word32
1024))
  decide :: LeiosOutstanding Int
-> Map LeiosPoint PeerOffer
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
decide LeiosOutstanding Int
outstanding Map LeiosPoint PeerOffer
offers =
    LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map Int (Map LeiosPoint PeerOffer)
-> Map Int IsBigLedgerPeer
-> LeiosOutstanding Int
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
forall peer.
Ord peer =>
LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map peer (Map LeiosPoint PeerOffer)
-> Map peer IsBigLedgerPeer
-> LeiosOutstanding peer
-> (LeiosOutstanding peer, Map peer (NESeq LeiosFetchRequest),
    Map peer (NEMap LeiosPoint OfferPrune))
leiosFetchLogicIteration
      LeiosFetchStaticEnv
env
      SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
anyBounds
      ((SlotNo, Word64) -> Maybe (SlotNo, Word64)
forall a. a -> Maybe a
Just (SlotNo
forall a. Bounded a => a
minBound, Word64
priorityWindow))
      (Int
-> Map LeiosPoint PeerOffer -> Map Int (Map LeiosPoint PeerOffer)
forall k a. k -> a -> Map k a
Map.singleton Int
peerA Map LeiosPoint PeerOffer
offers)
      Map Int IsBigLedgerPeer
forall k a. Map k a
Map.empty
      LeiosOutstanding Int
outstanding
  (LeiosOutstanding Int
outstanding1, Map Int (NESeq LeiosFetchRequest)
reqs1, Map Int (NEMap LeiosPoint OfferPrune)
prunes1) = LeiosOutstanding Int
-> Map LeiosPoint PeerOffer
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
decide (Scenario -> LeiosOutstanding Int
scOutstanding (Scenario
empty Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& LeiosPoint -> Word32 -> Scenario -> Scenario
withMissingBody LeiosPoint
p Word32
1024)) Map LeiosPoint PeerOffer
offers0
  offers1 :: Map LeiosPoint PeerOffer
offers1 = Map LeiosPoint OfferPrune
-> Map LeiosPoint PeerOffer -> Map LeiosPoint PeerOffer
pruneOffers (Map LeiosPoint OfferPrune
-> (NEMap LeiosPoint OfferPrune -> Map LeiosPoint OfferPrune)
-> Maybe (NEMap LeiosPoint OfferPrune)
-> Map LeiosPoint OfferPrune
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Map LeiosPoint OfferPrune
forall k a. Map k a
Map.empty NEMap LeiosPoint OfferPrune -> Map LeiosPoint OfferPrune
forall k a. NEMap k a -> Map k a
NEMap.toMap (Int
-> Map Int (NEMap LeiosPoint OfferPrune)
-> Maybe (NEMap LeiosPoint OfferPrune)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Int
peerA Map Int (NEMap LeiosPoint OfferPrune)
prunes1)) Map LeiosPoint PeerOffer
offers0
  -- The reply arrived, but its write has not settled, so the body is not held
  -- yet.
  outstanding2 :: LeiosOutstanding Int
outstanding2 = Int
-> LeiosPoint
-> Word32
-> LeiosOutstanding Int
-> LeiosOutstanding Int
forall peer.
Ord peer =>
peer
-> LeiosPoint
-> Word32
-> LeiosOutstanding peer
-> LeiosOutstanding peer
refundEbRequest Int
peerA LeiosPoint
p Word32
1024 LeiosOutstanding Int
outstanding1
  (LeiosOutstanding Int
_, Map Int (NESeq LeiosFetchRequest)
reqs2, Map Int (NEMap LeiosPoint OfferPrune)
_) = LeiosOutstanding Int
-> Map LeiosPoint PeerOffer
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
decide LeiosOutstanding Int
outstanding2 Map LeiosPoint PeerOffer
offers1
  jobPool :: LeiosJobPool
jobPool =
    Word32 -> Int -> IntMap (TxHash, Word32) -> LeiosJobPool
Jobs.mkJobPool
      (LeiosFetchStaticEnv -> Word32
maxJobBytesSize LeiosFetchStaticEnv
env)
      (LeiosFetchStaticEnv -> Int
maxJobTxCount LeiosFetchStaticEnv
env)
      (Int -> (TxHash, Word32) -> IntMap (TxHash, Word32)
forall a. Int -> a -> IntMap a
IntMap.singleton Int
0 (Int -> TxHash
txHashOf Int
0, Word32
100))
  (LeiosOutstanding Int
_, Map Int (NESeq LeiosFetchRequest)
reqs3, Map Int (NEMap LeiosPoint OfferPrune)
_) = LeiosOutstanding Int
-> Map LeiosPoint PeerOffer
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
decide (LeiosPoint
-> LeiosJobPool -> LeiosOutstanding Int -> LeiosOutstanding Int
forall peer.
LeiosPoint
-> LeiosJobPool -> LeiosOutstanding peer -> LeiosOutstanding peer
acquireEbBody LeiosPoint
p LeiosJobPool
jobPool LeiosOutstanding Int
outstanding2) Map LeiosPoint PeerOffer
offers1

-- | A peer offers the body, and then the closure after a decision has read its
-- offers but before they are pruned. Whether the body was still to fetch or
-- already held, the closure is asked of the peer once the body is held.
test_closureOfferedMeanwhile :: IO ()
test_closureOfferedMeanwhile :: Assertion
test_closureOfferedMeanwhile = do
  Map Int (NESeq LeiosFetchRequest) -> IntSet
requestedOffsets (LeiosOutstanding Int -> Map Int (NESeq LeiosFetchRequest)
closureRequests LeiosOutstanding Int
missing) IntSet -> IntSet -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Int -> IntSet
IntSet.singleton Int
0
  Map Int (NESeq LeiosFetchRequest) -> IntSet
requestedOffsets (LeiosOutstanding Int -> Map Int (NESeq LeiosFetchRequest)
closureRequests (LeiosPoint
-> LeiosJobPool -> LeiosOutstanding Int -> LeiosOutstanding Int
forall peer.
LeiosPoint
-> LeiosJobPool -> LeiosOutstanding peer -> LeiosOutstanding peer
acquireEbBody LeiosPoint
p LeiosJobPool
jobPool LeiosOutstanding Int
missing)) IntSet -> IntSet -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Int -> IntSet
IntSet.singleton Int
0
 where
  p :: LeiosPoint
p = Word -> Char -> LeiosPoint
point Word
1 Char
'a'
  missing :: LeiosOutstanding Int
missing = Scenario -> LeiosOutstanding Int
scOutstanding (Scenario
empty Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& LeiosPoint -> Word32 -> Scenario -> Scenario
withMissingBody LeiosPoint
p Word32
1024)
  jobPool :: LeiosJobPool
jobPool =
    Word32 -> Int -> IntMap (TxHash, Word32) -> LeiosJobPool
Jobs.mkJobPool
      (LeiosFetchStaticEnv -> Word32
maxJobBytesSize LeiosFetchStaticEnv
env)
      (LeiosFetchStaticEnv -> Int
maxJobTxCount LeiosFetchStaticEnv
env)
      (Int -> (TxHash, Word32) -> IntMap (TxHash, Word32)
forall a. Int -> a -> IntMap a
IntMap.singleton Int
0 (Int -> TxHash
txHashOf Int
0, Word32
100))
  bodyOffered :: Map LeiosPoint PeerOffer
bodyOffered = LeiosPoint -> PeerOffer -> Map LeiosPoint PeerOffer
forall k a. k -> a -> Map k a
Map.singleton LeiosPoint
p (StrictMaybe (LeiosEbByteSizes 'SizeLimit)
-> OfferedHalves -> PeerOffer
MkPeerOffer StrictMaybe (LeiosEbByteSizes 'SizeLimit)
forall a. StrictMaybe a
SNothing (Word32 -> OfferedHalves
OfferedBody Word32
1024))
  closureOffered :: PeerOffer
closureOffered = StrictMaybe (LeiosEbByteSizes 'SizeLimit)
-> OfferedHalves -> PeerOffer
MkPeerOffer StrictMaybe (LeiosEbByteSizes 'SizeLimit)
forall a. StrictMaybe a
SNothing OfferedHalves
OfferedClosure
  decide :: LeiosOutstanding Int
-> Map LeiosPoint PeerOffer
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
decide LeiosOutstanding Int
outstanding Map LeiosPoint PeerOffer
offers =
    LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map Int (Map LeiosPoint PeerOffer)
-> Map Int IsBigLedgerPeer
-> LeiosOutstanding Int
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
forall peer.
Ord peer =>
LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map peer (Map LeiosPoint PeerOffer)
-> Map peer IsBigLedgerPeer
-> LeiosOutstanding peer
-> (LeiosOutstanding peer, Map peer (NESeq LeiosFetchRequest),
    Map peer (NEMap LeiosPoint OfferPrune))
leiosFetchLogicIteration
      LeiosFetchStaticEnv
env
      SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
anyBounds
      ((SlotNo, Word64) -> Maybe (SlotNo, Word64)
forall a. a -> Maybe a
Just (SlotNo
forall a. Bounded a => a
minBound, Word64
priorityWindow))
      (Int
-> Map LeiosPoint PeerOffer -> Map Int (Map LeiosPoint PeerOffer)
forall k a. k -> a -> Map k a
Map.singleton Int
peerA Map LeiosPoint PeerOffer
offers)
      Map Int IsBigLedgerPeer
forall k a. Map k a
Map.empty
      LeiosOutstanding Int
outstanding
  closureRequests :: LeiosOutstanding Int -> Map Int (NESeq LeiosFetchRequest)
closureRequests LeiosOutstanding Int
outstanding0 = Map Int (NESeq LeiosFetchRequest)
reqs
   where
    (LeiosOutstanding Int
outstanding1, Map Int (NESeq LeiosFetchRequest)
_, Map Int (NEMap LeiosPoint OfferPrune)
prunes) = LeiosOutstanding Int
-> Map LeiosPoint PeerOffer
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
decide LeiosOutstanding Int
outstanding0 Map LeiosPoint PeerOffer
bodyOffered
    offers :: Map LeiosPoint PeerOffer
offers =
      Map LeiosPoint OfferPrune
-> Map LeiosPoint PeerOffer -> Map LeiosPoint PeerOffer
pruneOffers
        (Map LeiosPoint OfferPrune
-> (NEMap LeiosPoint OfferPrune -> Map LeiosPoint OfferPrune)
-> Maybe (NEMap LeiosPoint OfferPrune)
-> Map LeiosPoint OfferPrune
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Map LeiosPoint OfferPrune
forall k a. Map k a
Map.empty NEMap LeiosPoint OfferPrune -> Map LeiosPoint OfferPrune
forall k a. NEMap k a -> Map k a
NEMap.toMap (Int
-> Map Int (NEMap LeiosPoint OfferPrune)
-> Maybe (NEMap LeiosPoint OfferPrune)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Int
peerA Map Int (NEMap LeiosPoint OfferPrune)
prunes))
        ((PeerOffer -> PeerOffer -> PeerOffer)
-> LeiosPoint
-> PeerOffer
-> Map LeiosPoint PeerOffer
-> Map LeiosPoint PeerOffer
forall k a. Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
Map.insertWith PeerOffer -> PeerOffer -> PeerOffer
forall a. Semigroup a => a -> a -> a
(<>) LeiosPoint
p PeerOffer
closureOffered Map LeiosPoint PeerOffer
bodyOffered)
    (LeiosOutstanding Int
_, Map Int (NESeq LeiosFetchRequest)
reqs, Map Int (NEMap LeiosPoint OfferPrune)
_) = LeiosOutstanding Int
-> Map LeiosPoint PeerOffer
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
decide (LeiosPoint
-> LeiosJobPool -> LeiosOutstanding Int -> LeiosOutstanding Int
forall peer.
LeiosPoint
-> LeiosJobPool -> LeiosOutstanding peer -> LeiosOutstanding peer
acquireEbBody LeiosPoint
p LeiosJobPool
jobPool (Int
-> LeiosPoint
-> Word32
-> LeiosOutstanding Int
-> LeiosOutstanding Int
forall peer.
Ord peer =>
peer
-> LeiosPoint
-> Word32
-> LeiosOutstanding peer
-> LeiosOutstanding peer
refundEbRequest Int
peerA LeiosPoint
p Word32
1024 LeiosOutstanding Int
outstanding1)) Map LeiosPoint PeerOffer
offers

-- | Once the node's own forge's writes of the endorser block at a point land,
-- a peer offering its body and its closure is asked for neither, and its whole
-- offer is pruned.
test_forgedNotFetched :: IO ()
test_forgedNotFetched :: Assertion
test_forgedNotFetched = do
  Map Int (NESeq LeiosFetchRequest) -> Assertion
assertNoRequests Map Int (NESeq LeiosFetchRequest)
reqs
  Map LeiosPoint OfferPrune
-> Map LeiosPoint PeerOffer -> Map LeiosPoint PeerOffer
pruneOffers (Map LeiosPoint OfferPrune
-> (NEMap LeiosPoint OfferPrune -> Map LeiosPoint OfferPrune)
-> Maybe (NEMap LeiosPoint OfferPrune)
-> Map LeiosPoint OfferPrune
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Map LeiosPoint OfferPrune
forall k a. Map k a
Map.empty NEMap LeiosPoint OfferPrune -> Map LeiosPoint OfferPrune
forall k a. NEMap k a -> Map k a
NEMap.toMap (Int
-> Map Int (NEMap LeiosPoint OfferPrune)
-> Maybe (NEMap LeiosPoint OfferPrune)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Int
peerA Map Int (NEMap LeiosPoint OfferPrune)
prunes)) Map LeiosPoint PeerOffer
offers Map LeiosPoint PeerOffer -> Map LeiosPoint PeerOffer -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Map LeiosPoint PeerOffer
forall k a. Map k a
Map.empty
 where
  p :: LeiosPoint
p = Word -> Char -> LeiosPoint
point Word
1 Char
'a'
  offers :: Map LeiosPoint PeerOffer
offers = LeiosPoint -> PeerOffer -> Map LeiosPoint PeerOffer
forall k a. k -> a -> Map k a
Map.singleton LeiosPoint
p (StrictMaybe (LeiosEbByteSizes 'SizeLimit)
-> OfferedHalves -> PeerOffer
MkPeerOffer StrictMaybe (LeiosEbByteSizes 'SizeLimit)
forall a. StrictMaybe a
SNothing (Word32 -> OfferedHalves
OfferedBodyAndClosure Word32
1024))
  (LeiosOutstanding Int
_, Map Int (NESeq LeiosFetchRequest)
reqs, Map Int (NEMap LeiosPoint OfferPrune)
prunes) =
    LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map Int (Map LeiosPoint PeerOffer)
-> Map Int IsBigLedgerPeer
-> LeiosOutstanding Int
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
forall peer.
Ord peer =>
LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map peer (Map LeiosPoint PeerOffer)
-> Map peer IsBigLedgerPeer
-> LeiosOutstanding peer
-> (LeiosOutstanding peer, Map peer (NESeq LeiosFetchRequest),
    Map peer (NEMap LeiosPoint OfferPrune))
leiosFetchLogicIteration
      LeiosFetchStaticEnv
env
      SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
anyBounds
      ((SlotNo, Word64) -> Maybe (SlotNo, Word64)
forall a. a -> Maybe a
Just (SlotNo
forall a. Bounded a => a
minBound, Word64
priorityWindow))
      (Int
-> Map LeiosPoint PeerOffer -> Map Int (Map LeiosPoint PeerOffer)
forall k a. k -> a -> Map k a
Map.singleton Int
peerA Map LeiosPoint PeerOffer
offers)
      Map Int IsBigLedgerPeer
forall k a. Map k a
Map.empty
      ( (LeiosOutstanding Int, [LeiosAcquisition]) -> LeiosOutstanding Int
forall a b. (a, b) -> a
fst
          ( ElectionId
-> EndorserBlockHash
-> Word32
-> LeiosOutstanding Int
-> (LeiosOutstanding Int, [LeiosAcquisition])
forall peer.
ElectionId
-> EndorserBlockHash
-> Word32
-> LeiosOutstanding peer
-> (LeiosOutstanding peer, [LeiosAcquisition])
holdForgedEb
              (SlotNo -> KeyHash BlockIssuer -> ElectionId
ElectionId (Word64 -> SlotNo
SlotNo Word64
1) KeyHash BlockIssuer
forall (r :: KeyRole). KeyHash r
fixtureElectee)
              (Char -> EndorserBlockHash
eb Char
'a')
              Word32
1024
              (Scenario -> LeiosOutstanding Int
scOutstanding (Scenario
empty Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& LeiosPoint -> Word32 -> Scenario -> Scenario
withMissingBody LeiosPoint
p Word32
1024))
          )
      )

-- | An endorser block rejected as too big, then offered again at the same point,
-- under bounds that admit it. The decision logic does not consult the bounds
-- for a body it holds, so this guards against it starting to.
test_noRefetchOversized :: IO ()
test_noRefetchOversized :: Assertion
test_noRefetchOversized =
  Scenario
empty
    Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& LeiosPoint -> Word32 -> Scenario -> Scenario
withMissingBody (Word -> Char -> LeiosPoint
point Word
1 Char
'a') Word32
1024
    Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& (LeiosOutstanding Int -> LeiosOutstanding Int)
-> Scenario -> Scenario
onOutstanding
      (LeiosPoint
-> LeiosJobPool -> LeiosOutstanding Int -> LeiosOutstanding Int
forall peer.
LeiosPoint
-> LeiosJobPool -> LeiosOutstanding peer -> LeiosOutstanding peer
acquireEbBody (Word -> Char -> LeiosPoint
point Word
1 Char
'a') LeiosJobPool
Jobs.emptyJobPool)
    Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& Int -> [LeiosPoint] -> Scenario -> Scenario
offersBody Int
peerA [Word -> Char -> LeiosPoint
point Word
1 Char
'a']
    Scenario
-> (Scenario -> Map Int (NESeq LeiosFetchRequest))
-> Map Int (NESeq LeiosFetchRequest)
forall a b. a -> (a -> b) -> b
& (SlotNo
 -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Scenario -> Map Int (NESeq LeiosFetchRequest)
runIterationWith (\SlotNo
_slot -> LeiosEbByteSizes 'SizeLimit
-> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
forall a b. b -> Either a b
Right (LeiosEbByteSizes 'SizeLimit -> LeiosEbByteSizes 'SizeLimit
idLeiosEbByteSizesLimit (Word32 -> Word64 -> LeiosEbByteSizes 'SizeLimit
forall (r :: SizeRole). Word32 -> Word64 -> LeiosEbByteSizes r
MkLeiosEbByteSizes Word32
1024 Word64
5000)))
    Map Int (NESeq LeiosFetchRequest)
-> (Map Int (NESeq LeiosFetchRequest) -> Assertion) -> Assertion
forall a b. a -> (a -> b) -> b
& Map Int (NESeq LeiosFetchRequest) -> Assertion
assertNoRequests

-- | A peer offers only the body, with no bounds of its own, at a slot beyond the
-- range the ledger's bounds can be forecast for. Nothing is requested and the
-- offer is not pruned, so a later iteration whose forecast reaches the slot
-- requests the body from that same offer.
test_bodyBeyondForecastKept :: IO ()
test_bodyBeyondForecastKept :: Assertion
test_bodyBeyondForecastKept = do
  Map Int (NESeq LeiosFetchRequest) -> Assertion
assertNoRequests Map Int (NESeq LeiosFetchRequest)
reqs1
  HasCallStack => String -> Bool -> Assertion
String -> Bool -> Assertion
assertBool String
"the offer is pruned" (Int -> Map Int (NEMap LeiosPoint OfferPrune) -> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.notMember Int
peerA Map Int (NEMap LeiosPoint OfferPrune)
prunes1)
  Int
-> LeiosPoint
-> Word32
-> Map Int (NESeq LeiosFetchRequest)
-> Assertion
assertBodyRequest Int
peerA LeiosPoint
p Word32
1024 Map Int (NESeq LeiosFetchRequest)
reqs2
 where
  p :: LeiosPoint
p = Word -> Char -> LeiosPoint
point Word
1 Char
'a'
  offers0 :: Map LeiosPoint PeerOffer
offers0 = LeiosPoint -> PeerOffer -> Map LeiosPoint PeerOffer
forall k a. k -> a -> Map k a
Map.singleton LeiosPoint
p (StrictMaybe (LeiosEbByteSizes 'SizeLimit)
-> OfferedHalves -> PeerOffer
MkPeerOffer StrictMaybe (LeiosEbByteSizes 'SizeLimit)
forall a. StrictMaybe a
SNothing (Word32 -> OfferedHalves
OfferedBody Word32
1024))
  beyondForecast :: SlotNo -> Either OutsideForecastRange b
beyondForecast SlotNo
slot = OutsideForecastRange -> Either OutsideForecastRange b
forall a b. a -> Either a b
Left (WithOrigin SlotNo -> SlotNo -> SlotNo -> OutsideForecastRange
OutsideForecastRange WithOrigin SlotNo
forall t. WithOrigin t
Origin SlotNo
slot SlotNo
slot)
  decide :: (SlotNo
 -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> LeiosOutstanding Int
-> Map LeiosPoint PeerOffer
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
decide SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
forecastEbBounds LeiosOutstanding Int
outstanding Map LeiosPoint PeerOffer
offers =
    LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map Int (Map LeiosPoint PeerOffer)
-> Map Int IsBigLedgerPeer
-> LeiosOutstanding Int
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
forall peer.
Ord peer =>
LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map peer (Map LeiosPoint PeerOffer)
-> Map peer IsBigLedgerPeer
-> LeiosOutstanding peer
-> (LeiosOutstanding peer, Map peer (NESeq LeiosFetchRequest),
    Map peer (NEMap LeiosPoint OfferPrune))
leiosFetchLogicIteration
      LeiosFetchStaticEnv
env
      SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
forecastEbBounds
      ((SlotNo, Word64) -> Maybe (SlotNo, Word64)
forall a. a -> Maybe a
Just (SlotNo
forall a. Bounded a => a
minBound, Word64
priorityWindow))
      (Int
-> Map LeiosPoint PeerOffer -> Map Int (Map LeiosPoint PeerOffer)
forall k a. k -> a -> Map k a
Map.singleton Int
peerA Map LeiosPoint PeerOffer
offers)
      Map Int IsBigLedgerPeer
forall k a. Map k a
Map.empty
      LeiosOutstanding Int
outstanding
  (LeiosOutstanding Int
outstanding1, Map Int (NESeq LeiosFetchRequest)
reqs1, Map Int (NEMap LeiosPoint OfferPrune)
prunes1) =
    (SlotNo
 -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> LeiosOutstanding Int
-> Map LeiosPoint PeerOffer
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
decide SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
forall {b}. SlotNo -> Either OutsideForecastRange b
beyondForecast (Scenario -> LeiosOutstanding Int
scOutstanding (Scenario
empty Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& LeiosPoint -> Word32 -> Scenario -> Scenario
withMissingBody LeiosPoint
p Word32
1024)) Map LeiosPoint PeerOffer
offers0
  offers1 :: Map LeiosPoint PeerOffer
offers1 = Map LeiosPoint OfferPrune
-> Map LeiosPoint PeerOffer -> Map LeiosPoint PeerOffer
pruneOffers (Map LeiosPoint OfferPrune
-> (NEMap LeiosPoint OfferPrune -> Map LeiosPoint OfferPrune)
-> Maybe (NEMap LeiosPoint OfferPrune)
-> Map LeiosPoint OfferPrune
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Map LeiosPoint OfferPrune
forall k a. Map k a
Map.empty NEMap LeiosPoint OfferPrune -> Map LeiosPoint OfferPrune
forall k a. NEMap k a -> Map k a
NEMap.toMap (Int
-> Map Int (NEMap LeiosPoint OfferPrune)
-> Maybe (NEMap LeiosPoint OfferPrune)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Int
peerA Map Int (NEMap LeiosPoint OfferPrune)
prunes1)) Map LeiosPoint PeerOffer
offers0
  (LeiosOutstanding Int
_, Map Int (NESeq LeiosFetchRequest)
reqs2, Map Int (NEMap LeiosPoint OfferPrune)
_) = (SlotNo
 -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> LeiosOutstanding Int
-> Map LeiosPoint PeerOffer
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
decide SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
anyBounds LeiosOutstanding Int
outstanding1 Map LeiosPoint PeerOffer
offers1

test_perPeerByteBudget :: IO ()
test_perPeerByteBudget :: Assertion
test_perPeerByteBudget =
  Scenario
empty
    Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& LeiosPoint -> Word32 -> Scenario -> Scenario
withMissingBody (Word -> Char -> LeiosPoint
point Word
1 Char
'a') Word32
1024
    Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& Int -> Word32 -> Scenario -> Scenario
withRequestedBytesPerPeer Int
peerA (LeiosFetchStaticEnv -> Word32
maxRequestedBytesSizePerPeer LeiosFetchStaticEnv
env Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
+ Word32
1)
    Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& Int -> [LeiosPoint] -> Scenario -> Scenario
offersBody Int
peerA [Word -> Char -> LeiosPoint
point Word
1 Char
'a']
    Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& Int -> [LeiosPoint] -> Scenario -> Scenario
offersBody Int
peerB [Word -> Char -> LeiosPoint
point Word
1 Char
'a']
    Scenario
-> (Scenario -> Map Int (NESeq LeiosFetchRequest))
-> Map Int (NESeq LeiosFetchRequest)
forall a b. a -> (a -> b) -> b
& Scenario -> Map Int (NESeq LeiosFetchRequest)
runIteration
    Map Int (NESeq LeiosFetchRequest)
-> (Map Int (NESeq LeiosFetchRequest) -> Assertion) -> Assertion
forall a b. a -> (a -> b) -> b
& [Int] -> Map Int (NESeq LeiosFetchRequest) -> Assertion
assertRequestPeers [Int
peerB]

-- | A peer is asked for a body only if it fits in what remains of the peer's
-- cap, and the first body that does not fit ends the peer's walk, so a smaller
-- one offered after it is not asked for either.
test_perPeerByteBudgetHard :: IO ()
test_perPeerByteBudgetHard :: Assertion
test_perPeerByteBudgetHard = do
  Word32 -> [LeiosPoint]
bodiesRequested (Word32
cap Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
- Word32
1024) [LeiosPoint] -> [LeiosPoint] -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= [Word -> Char -> LeiosPoint
point Word
1 Char
'a']
  Word32 -> [LeiosPoint]
bodiesRequested (Word32
cap Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
- Word32
1023) [LeiosPoint] -> [LeiosPoint] -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= []
 where
  cap :: Word32
cap = LeiosFetchStaticEnv -> Word32
maxRequestedBytesSizePerPeer LeiosFetchStaticEnv
env
  bodiesRequested :: Word32 -> [LeiosPoint]
bodiesRequested Word32
used =
    let reqs :: Map Int (NESeq LeiosFetchRequest)
reqs =
          Scenario
empty
            Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& LeiosPoint -> Word32 -> Scenario -> Scenario
withMissingBody (Word -> Char -> LeiosPoint
point Word
1 Char
'a') Word32
1024
            Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& LeiosPoint -> Word32 -> Scenario -> Scenario
withMissingBody (Word -> Char -> LeiosPoint
point Word
2 Char
'b') Word32
100
            Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& Int -> Word32 -> Scenario -> Scenario
withRequestedBytesPerPeer Int
peerA Word32
used
            Scenario -> (Scenario -> Scenario) -> Scenario
forall a b. a -> (a -> b) -> b
& Int -> [LeiosPoint] -> Scenario -> Scenario
offersBody Int
peerA [Word -> Char -> LeiosPoint
point Word
1 Char
'a', Word -> Char -> LeiosPoint
point Word
2 Char
'b']
            -- Both points are in the high-priority tier, which is walked
            -- oldest first.
            Scenario
-> (Scenario -> Map Int (NESeq LeiosFetchRequest))
-> Map Int (NESeq LeiosFetchRequest)
forall a b. a -> (a -> b) -> b
& SlotNo -> Scenario -> Map Int (NESeq LeiosFetchRequest)
runIterationAt (Word64 -> SlotNo
SlotNo Word64
2)
     in [LeiosBlockRequest
r.lbrPoint | LeiosBlockRequest LeiosBlockRequest
r <- [LeiosFetchRequest]
-> (NESeq LeiosFetchRequest -> [LeiosFetchRequest])
-> Maybe (NESeq LeiosFetchRequest)
-> [LeiosFetchRequest]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] NESeq LeiosFetchRequest -> [LeiosFetchRequest]
forall a. NESeq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList (Int
-> Map Int (NESeq LeiosFetchRequest)
-> Maybe (NESeq LeiosFetchRequest)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Int
peerA Map Int (NESeq LeiosFetchRequest)
reqs)]

test_focusCertifiedPruned :: IO ()
test_focusCertifiedPruned :: Assertion
test_focusCertifiedPruned =
  (Map ElectionId EndorserBlockHash -> Int
forall k a. Map k a -> Int
Map.size (LeiosOutstanding (ZonkAny 0) -> Map ElectionId EndorserBlockHash
forall peer.
LeiosOutstanding peer -> Map ElectionId EndorserBlockHash
elFocus LeiosOutstanding (ZonkAny 0)
forall {peer}. LeiosOutstanding peer
outstanding), Map LeiosPoint EbState -> Int
forall k a. Map k a -> Int
Map.size (LeiosOutstanding (ZonkAny 1) -> Map LeiosPoint EbState
forall peer. LeiosOutstanding peer -> Map LeiosPoint EbState
ebState LeiosOutstanding (ZonkAny 1)
forall {peer}. LeiosOutstanding peer
outstanding)) (Int, Int) -> (Int, Int) -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= (Int
0, Int
0)
 where
  outstanding :: LeiosOutstanding peer
outstanding =
    ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
focusCertifiedEb (SlotNo -> KeyHash BlockIssuer -> ElectionId
ElectionId (Word64 -> SlotNo
SlotNo Word64
10) KeyHash BlockIssuer
forall (r :: KeyRole). KeyHash r
fixtureElectee) (Char -> EndorserBlockHash
eb Char
'a') (LeiosOutstanding peer -> LeiosOutstanding peer)
-> LeiosOutstanding peer -> LeiosOutstanding peer
forall a b. (a -> b) -> a -> b
$
      StdGen -> SlotNo -> LeiosOutstanding peer
forall peer. StdGen -> SlotNo -> LeiosOutstanding peer
emptyLeiosOutstanding (Int -> StdGen
mkStdGen Int
0) (Word64 -> SlotNo
SlotNo Word64
20)

-- | An announcement focuses an election on its endorser block, and a second
-- announcement for that election does not move the focus. A verified
-- certificate for the second does, and tracks its point, so a peer offering
-- both is asked only for the certified one. Its offer of the other is kept, in
-- case some election fetches that later.
test_focusCertifiedEb :: IO ()
test_focusCertifiedEb :: Assertion
test_focusCertifiedEb = do
  ElectionId
-> Map ElectionId EndorserBlockHash -> Maybe EndorserBlockHash
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup ElectionId
elId (LeiosOutstanding (ZonkAny 2) -> Map ElectionId EndorserBlockHash
forall peer.
LeiosOutstanding peer -> Map ElectionId EndorserBlockHash
elFocus LeiosOutstanding (ZonkAny 2)
forall {peer}. LeiosOutstanding peer
announced) Maybe EndorserBlockHash -> Maybe EndorserBlockHash -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= EndorserBlockHash -> Maybe EndorserBlockHash
forall a. a -> Maybe a
Just (Char -> EndorserBlockHash
eb Char
'a')
  ElectionId
-> Map ElectionId EndorserBlockHash -> Maybe EndorserBlockHash
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup ElectionId
elId (LeiosOutstanding (ZonkAny 3) -> Map ElectionId EndorserBlockHash
forall peer.
LeiosOutstanding peer -> Map ElectionId EndorserBlockHash
elFocus LeiosOutstanding (ZonkAny 3)
forall {peer}. LeiosOutstanding peer
certified) Maybe EndorserBlockHash -> Maybe EndorserBlockHash -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= EndorserBlockHash -> Maybe EndorserBlockHash
forall a. a -> Maybe a
Just (Char -> EndorserBlockHash
eb Char
'b')
  LeiosPoint -> Map LeiosPoint EbState -> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.member LeiosPoint
pB (LeiosOutstanding (ZonkAny 4) -> Map LeiosPoint EbState
forall peer. LeiosOutstanding peer -> Map LeiosPoint EbState
ebState LeiosOutstanding (ZonkAny 4)
forall {peer}. LeiosOutstanding peer
certified) Bool -> Bool -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Bool
True
  [LeiosBlockRequest
r.lbrPoint | LeiosBlockRequest LeiosBlockRequest
r <- [LeiosFetchRequest]
-> (NESeq LeiosFetchRequest -> [LeiosFetchRequest])
-> Maybe (NESeq LeiosFetchRequest)
-> [LeiosFetchRequest]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] NESeq LeiosFetchRequest -> [LeiosFetchRequest]
forall a. NESeq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList (Int
-> Map Int (NESeq LeiosFetchRequest)
-> Maybe (NESeq LeiosFetchRequest)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Int
peerA Map Int (NESeq LeiosFetchRequest)
reqs)] [LeiosPoint] -> [LeiosPoint] -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= [LeiosPoint
pB]
  [LeiosPoint]
-> (NEMap LeiosPoint OfferPrune -> [LeiosPoint])
-> Maybe (NEMap LeiosPoint OfferPrune)
-> [LeiosPoint]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] (NonEmpty LeiosPoint -> [LeiosPoint]
forall a. NonEmpty a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList (NonEmpty LeiosPoint -> [LeiosPoint])
-> (NEMap LeiosPoint OfferPrune -> NonEmpty LeiosPoint)
-> NEMap LeiosPoint OfferPrune
-> [LeiosPoint]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. NEMap LeiosPoint OfferPrune -> NonEmpty LeiosPoint
forall k a. NEMap k a -> NonEmpty k
NEMap.keys) (Int
-> Map Int (NEMap LeiosPoint OfferPrune)
-> Maybe (NEMap LeiosPoint OfferPrune)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Int
peerA Map Int (NEMap LeiosPoint OfferPrune)
prunes) [LeiosPoint] -> [LeiosPoint] -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= [LeiosPoint
pB]
 where
  elId :: ElectionId
elId = SlotNo -> KeyHash BlockIssuer -> ElectionId
ElectionId (Word64 -> SlotNo
SlotNo Word64
10) KeyHash BlockIssuer
forall (r :: KeyRole). KeyHash r
fixtureElectee
  pA :: LeiosPoint
pA = Word -> Char -> LeiosPoint
point Word
10 Char
'a'
  pB :: LeiosPoint
pB = Word -> Char -> LeiosPoint
point Word
10 Char
'b'
  -- The first announcement takes the election's focus and tracks its point;
  -- the second changes nothing.
  announced :: LeiosOutstanding peer
announced =
    ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
focusElectionIfUnfocused ElectionId
elId (Char -> EndorserBlockHash
eb Char
'b')
      (LeiosOutstanding peer -> LeiosOutstanding peer)
-> (LeiosOutstanding peer -> LeiosOutstanding peer)
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
focusElectionIfUnfocused ElectionId
elId (Char -> EndorserBlockHash
eb Char
'a')
      (LeiosOutstanding peer -> LeiosOutstanding peer)
-> (LeiosOutstanding peer -> LeiosOutstanding peer)
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding peer
-> LeiosOutstanding peer
recordReferencedPoint LeiosPoint
pA StrictMaybe RelativeTime
forall a. StrictMaybe a
SNothing
      (LeiosOutstanding peer -> LeiosOutstanding peer)
-> LeiosOutstanding peer -> LeiosOutstanding peer
forall a b. (a -> b) -> a -> b
$ StdGen -> SlotNo -> LeiosOutstanding peer
forall peer. StdGen -> SlotNo -> LeiosOutstanding peer
emptyLeiosOutstanding (Int -> StdGen
mkStdGen Int
0) (Word64 -> SlotNo
SlotNo Word64
0)
  certified :: LeiosOutstanding peer
certified = ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
focusCertifiedEb ElectionId
elId (Char -> EndorserBlockHash
eb Char
'b') LeiosOutstanding peer
forall {peer}. LeiosOutstanding peer
announced
  offers :: Map LeiosPoint PeerOffer
offers = [(LeiosPoint, PeerOffer)] -> Map LeiosPoint PeerOffer
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList [(LeiosPoint
p, StrictMaybe (LeiosEbByteSizes 'SizeLimit)
-> OfferedHalves -> PeerOffer
MkPeerOffer StrictMaybe (LeiosEbByteSizes 'SizeLimit)
forall a. StrictMaybe a
SNothing (Word32 -> OfferedHalves
OfferedBody Word32
1024)) | LeiosPoint
p <- [LeiosPoint
pA, LeiosPoint
pB]]
  (LeiosOutstanding Int
_, Map Int (NESeq LeiosFetchRequest)
reqs, Map Int (NEMap LeiosPoint OfferPrune)
prunes) =
    LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map Int (Map LeiosPoint PeerOffer)
-> Map Int IsBigLedgerPeer
-> LeiosOutstanding Int
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
forall peer.
Ord peer =>
LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map peer (Map LeiosPoint PeerOffer)
-> Map peer IsBigLedgerPeer
-> LeiosOutstanding peer
-> (LeiosOutstanding peer, Map peer (NESeq LeiosFetchRequest),
    Map peer (NEMap LeiosPoint OfferPrune))
leiosFetchLogicIteration
      LeiosFetchStaticEnv
env
      SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
anyBounds
      ((SlotNo, Word64) -> Maybe (SlotNo, Word64)
forall a. a -> Maybe a
Just (Word64 -> SlotNo
SlotNo Word64
11, Word64
priorityWindow))
      (Int
-> Map LeiosPoint PeerOffer -> Map Int (Map LeiosPoint PeerOffer)
forall k a. k -> a -> Map k a
Map.singleton Int
peerA Map LeiosPoint PeerOffer
offers)
      Map Int IsBigLedgerPeer
forall k a. Map k a
Map.empty
      LeiosOutstanding Int
forall {peer}. LeiosOutstanding peer
certified

test_bigLedgerPeerBudget :: IO ()
test_bigLedgerPeerBudget :: Assertion
test_bigLedgerPeerBudget = do
  -- past the ordinary cap, an ordinary peer is asked for nothing ...
  Map Int IsBigLedgerPeer -> Word32 -> IntSet
run Map Int IsBigLedgerPeer
forall k a. Map k a
ordinary (Word32
ordinaryCap Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
+ Word32
1) IntSet -> IntSet -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= IntSet
IntSet.empty
  -- ... but a big-ledger peer still has budget for the whole pool at once
  Map Int IsBigLedgerPeer -> Word32 -> IntSet
run Map Int IsBigLedgerPeer
bigLedger (Word32
ordinaryCap Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
+ Word32
1) IntSet -> IntSet -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= [Int] -> IntSet
IntSet.fromList [Int]
offsets
  -- past even the big-ledger cap, though, a big-ledger peer is bounded too
  Map Int IsBigLedgerPeer -> Word32 -> IntSet
run Map Int IsBigLedgerPeer
bigLedger (Word32
bigLedgerCap Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
+ Word32
1) IntSet -> IntSet -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= IntSet
IntSet.empty
 where
  offsets :: [Int]
offsets = [Int
0 .. Int
4]
  p :: LeiosPoint
p = Word -> Char -> LeiosPoint
point Word
10 Char
'a'
  misses :: IntMap (TxHash, Word32)
misses = [(Int, (TxHash, Word32))] -> IntMap (TxHash, Word32)
forall a. [(Int, a)] -> IntMap a
IntMap.fromList [(Int
off, (Int -> TxHash
txHashOf Int
off, Word32
100)) | Int
off <- [Int]
offsets]
  jobPool :: LeiosJobPool
jobPool = Word32 -> Int -> IntMap (TxHash, Word32) -> LeiosJobPool
Jobs.mkJobPool (LeiosFetchStaticEnv -> Word32
maxJobBytesSize LeiosFetchStaticEnv
env) (LeiosFetchStaticEnv -> Int
maxJobTxCount LeiosFetchStaticEnv
env) IntMap (TxHash, Word32)
misses
  -- The body is already held in these runs, so the offer names no size; only
  -- its closure half is consulted.
  offers :: Map Int (Map LeiosPoint PeerOffer)
offers = Int
-> Map LeiosPoint PeerOffer -> Map Int (Map LeiosPoint PeerOffer)
forall k a. k -> a -> Map k a
Map.singleton Int
peerA (Map LeiosPoint PeerOffer -> Map Int (Map LeiosPoint PeerOffer))
-> Map LeiosPoint PeerOffer -> Map Int (Map LeiosPoint PeerOffer)
forall a b. (a -> b) -> a -> b
$ LeiosPoint -> PeerOffer -> Map LeiosPoint PeerOffer
forall k a. k -> a -> Map k a
Map.singleton LeiosPoint
p (StrictMaybe (LeiosEbByteSizes 'SizeLimit)
-> OfferedHalves -> PeerOffer
MkPeerOffer StrictMaybe (LeiosEbByteSizes 'SizeLimit)
forall a. StrictMaybe a
SNothing OfferedHalves
OfferedClosure)
  ordinaryCap :: Word32
ordinaryCap = LeiosFetchStaticEnv -> Word32
maxRequestedBytesSizePerPeer LeiosFetchStaticEnv
env
  bigLedgerCap :: Word32
bigLedgerCap = LeiosFetchStaticEnv -> Word32
maxRequestedBytesSizePerBigLedgerPeer LeiosFetchStaticEnv
env
  -- hold the body (so the pool is live), with the peer's in-flight bytes
  -- preloaded to 'used'
  run :: Map Int IsBigLedgerPeer -> Word32 -> IntSet
run Map Int IsBigLedgerPeer
bigLedgerPeers Word32
used =
    let outstanding :: LeiosOutstanding Int
outstanding =
          (\LeiosOutstanding Int
o -> LeiosOutstanding Int
o{requestedBytesSizePerPeer = Map.singleton peerA used})
            -- the election fetching it, without which nothing is requested
            (LeiosOutstanding Int -> LeiosOutstanding Int)
-> (LeiosOutstanding Int -> LeiosOutstanding Int)
-> LeiosOutstanding Int
-> LeiosOutstanding Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ElectionId
-> EndorserBlockHash
-> LeiosOutstanding Int
-> LeiosOutstanding Int
forall peer.
ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
focusElectionIfUnfocused (SlotNo -> KeyHash BlockIssuer -> ElectionId
ElectionId (Word64 -> SlotNo
SlotNo Word64
10) KeyHash BlockIssuer
forall (r :: KeyRole). KeyHash r
fixtureElectee) (Char -> EndorserBlockHash
eb Char
'a')
            (LeiosOutstanding Int -> LeiosOutstanding Int)
-> (LeiosOutstanding Int -> LeiosOutstanding Int)
-> LeiosOutstanding Int
-> LeiosOutstanding Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LeiosPoint
-> LeiosJobPool -> LeiosOutstanding Int -> LeiosOutstanding Int
forall peer.
LeiosPoint
-> LeiosJobPool -> LeiosOutstanding peer -> LeiosOutstanding peer
acquireEbBody LeiosPoint
p LeiosJobPool
jobPool
            (LeiosOutstanding Int -> LeiosOutstanding Int)
-> (LeiosOutstanding Int -> LeiosOutstanding Int)
-> LeiosOutstanding Int
-> LeiosOutstanding Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding Int
-> LeiosOutstanding Int
forall peer.
LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding peer
-> LeiosOutstanding peer
recordReferencedPoint LeiosPoint
p StrictMaybe RelativeTime
forall a. StrictMaybe a
SNothing
            (LeiosOutstanding Int -> LeiosOutstanding Int)
-> LeiosOutstanding Int -> LeiosOutstanding Int
forall a b. (a -> b) -> a -> b
$ StdGen -> SlotNo -> LeiosOutstanding Int
forall peer. StdGen -> SlotNo -> LeiosOutstanding peer
emptyLeiosOutstanding (Int -> StdGen
mkStdGen Int
0) (Word64 -> SlotNo
SlotNo Word64
0)
        (LeiosOutstanding Int
_o, Map Int (NESeq LeiosFetchRequest)
reqs, Map Int (NEMap LeiosPoint OfferPrune)
_d) =
          LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map Int (Map LeiosPoint PeerOffer)
-> Map Int IsBigLedgerPeer
-> LeiosOutstanding Int
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
forall peer.
Ord peer =>
LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map peer (Map LeiosPoint PeerOffer)
-> Map peer IsBigLedgerPeer
-> LeiosOutstanding peer
-> (LeiosOutstanding peer, Map peer (NESeq LeiosFetchRequest),
    Map peer (NEMap LeiosPoint OfferPrune))
leiosFetchLogicIteration
            LeiosFetchStaticEnv
env
            SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
anyBounds
            ((SlotNo, Word64) -> Maybe (SlotNo, Word64)
forall a. a -> Maybe a
Just (Word64 -> SlotNo
SlotNo Word64
11, Word64
priorityWindow))
            Map Int (Map LeiosPoint PeerOffer)
offers
            Map Int IsBigLedgerPeer
bigLedgerPeers
            LeiosOutstanding Int
outstanding
     in Map Int (NESeq LeiosFetchRequest) -> IntSet
requestedOffsets Map Int (NESeq LeiosFetchRequest)
reqs
  ordinary :: Map k a
ordinary = Map k a
forall k a. Map k a
Map.empty
  bigLedger :: Map Int IsBigLedgerPeer
bigLedger = Int -> IsBigLedgerPeer -> Map Int IsBigLedgerPeer
forall k a. k -> a -> Map k a
Map.singleton Int
peerA IsBigLedgerPeer
IsBigLedgerPeer

test_pickJobs :: IO ()
test_pickJobs :: Assertion
test_pickJobs = do
  -- across seeds the draw isn't pinned to the lowest id, and every draw is a
  -- real job id.
  let drawn :: Set Int
drawn = [Int] -> Set Int
forall a. Ord a => [a] -> Set a
Set.fromList [Int
i | Int
s <- [Int
0 .. Int
99], Just Int
i <- [LeiosJobPool -> IntSet -> Int -> Maybe Int
pickId LeiosJobPool
pool0 IntSet
IntSet.empty Int
s]]
  HasCallStack => String -> Bool -> Assertion
String -> Bool -> Assertion
assertBool String
"shuffles: more than one distinct job is drawn" (Set Int -> Int
forall a. Set a -> Int
Set.size Set Int
drawn Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1)
  HasCallStack => String -> Bool -> Assertion
String -> Bool -> Assertion
assertBool String
"only ever draws real job ids" (Set Int
drawn Set Int -> Set Int -> Bool
forall a. Ord a => Set a -> Set a -> Bool
`Set.isSubsetOf` [Int] -> Set Int
forall a. Ord a => [a] -> Set a
Set.fromList [Int
0 .. Int
5])
  -- an excluded job is never drawn: exclude all but job 5.
  [Int] -> Set Int
forall a. Ord a => [a] -> Set a
Set.fromList [Int
i | Int
s <- [Int
0 .. Int
50], Just Int
i <- [LeiosJobPool -> IntSet -> Int -> Maybe Int
pickId LeiosJobPool
pool0 ([Int] -> IntSet
IntSet.fromList [Int
0 .. Int
4]) Int
s]]
    Set Int -> Set Int -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Int -> Set Int
forall a. a -> Set a
Set.singleton Int
5
  -- the least-requested bucket wins regardless of the draw: force job 0 to
  -- multiplicity 1 (by excluding the rest), then an unrestricted draw comes
  -- only from the still-least-requested jobs 1..5, never job 0.
  case StdGen
-> IntSet
-> LeiosJobPool
-> Maybe (LeiosJobId, LeiosJob, LeiosJobPool, StdGen)
Jobs.pickLeastRequestedJobExcept (Int -> StdGen
mkStdGen Int
0) ([Int] -> IntSet
IntSet.fromList [Int
1 .. Int
5]) LeiosJobPool
pool0 of
    Maybe (LeiosJobId, LeiosJob, LeiosJobPool, StdGen)
Nothing -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure String
"forced pick of the sole non-excluded job failed"
    Just (LeiosJobId
_jid, LeiosJob
_job, LeiosJobPool
pool1, StdGen
_prng') -> do
      let drawnFromPool1 :: Set Int
drawnFromPool1 = [Int] -> Set Int
forall a. Ord a => [a] -> Set a
Set.fromList [Int
i | Int
s <- [Int
0 .. Int
50], Just Int
i <- [LeiosJobPool -> IntSet -> Int -> Maybe Int
pickId LeiosJobPool
pool1 IntSet
IntSet.empty Int
s]]
      HasCallStack => String -> Bool -> Assertion
String -> Bool -> Assertion
assertBool
        String
"least-requested bucket wins: job 0 (multiplicity 1) is not drawn"
        (Bool -> Bool
not (Int
0 Int -> Set Int -> Bool
forall a. Ord a => a -> Set a -> Bool
`Set.member` Set Int
drawnFromPool1))
      HasCallStack => String -> Bool -> Assertion
String -> Bool -> Assertion
assertBool String
"still shuffles among the least-requested jobs" (Set Int -> Int
forall a. Set a -> Int
Set.size Set Int
drawnFromPool1 Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1)
 where
  misses :: IntMap (TxHash, Word32)
misses = [(Int, (TxHash, Word32))] -> IntMap (TxHash, Word32)
forall a. [(Int, a)] -> IntMap a
IntMap.fromList [(Int
off, (Int -> TxHash
txHashOf Int
off, Word32
100)) | Int
off <- [Int
0 .. Int
5]]
  -- 'maxJobTxCount' 1 makes each tx its own job, so job ids 0..5 all start at
  -- multiplicity 0 (one bucket).
  pool0 :: LeiosJobPool
pool0 = Word32 -> Int -> IntMap (TxHash, Word32) -> LeiosJobPool
Jobs.mkJobPool Word32
1000000 Int
1 IntMap (TxHash, Word32)
misses
  pickId :: LeiosJobPool -> IntSet -> Int -> Maybe Int
pickId LeiosJobPool
pool IntSet
excluded Int
s =
    case StdGen
-> IntSet
-> LeiosJobPool
-> Maybe (LeiosJobId, LeiosJob, LeiosJobPool, StdGen)
Jobs.pickLeastRequestedJobExcept (Int -> StdGen
mkStdGen Int
s) IntSet
excluded LeiosJobPool
pool of
      Just (Jobs.MkLeiosJobId Int
i, LeiosJob
_job, LeiosJobPool
_pool', StdGen
_prng') -> Int -> Maybe Int
forall a. a -> Maybe a
Just Int
i
      Maybe (LeiosJobId, LeiosJob, LeiosJobPool, StdGen)
Nothing -> Maybe Int
forall a. Maybe a
Nothing

{-------------------------------------------------------------------------------
  Bookkeeping
-------------------------------------------------------------------------------}

-- | Decide, and settle what was decided, in any order: after every step, the
-- outstanding state's accounting of each peer's requests must agree with the
-- requests actually in flight.
prop_bookkeeping :: Property
prop_bookkeeping :: Property
prop_bookkeeping =
  Gen Setup -> (Setup -> Property) -> Property
forall a prop.
(Show a, Testable prop) =>
Gen a -> (a -> prop) -> Property
forAll Gen Setup
genSetup ((Setup -> Property) -> Property)
-> (Setup -> Property) -> Property
forall a b. (a -> b) -> a -> b
$ \Setup
setup ->
    Gen [Step] -> ([Step] -> Property) -> Property
forall a prop.
(Show a, Testable prop) =>
Gen a -> (a -> prop) -> Property
forAll (Int -> Gen Step -> Gen [Step]
forall a. Int -> Gen a -> Gen [a]
vectorOf Int
100 Gen Step
genStep) (([Step] -> Property) -> Property)
-> ([Step] -> Property) -> Property
forall a b. (a -> b) -> a -> b
$ \[Step]
steps ->
      let sims :: [Sim]
sims = (Sim -> Step -> Sim) -> Sim -> [Step] -> [Sim]
forall b a. (b -> a -> b) -> b -> [a] -> [b]
scanl (Setup -> Sim -> Step -> Sim
simulate Setup
setup) (Setup -> Sim
initialSim Setup
setup) [Step]
steps
          settled :: [LeiosFetchRequest]
settled = [LeiosFetchRequest
req | Sim
sim <- [Sim]
sims, (Int
_peer, LeiosFetchRequest
req) <- Sim -> [(Int, LeiosFetchRequest)]
simSettled Sim
sim]
       in String -> [String] -> Property -> Property
forall prop.
Testable prop =>
String -> [String] -> prop -> Property
tabulate String
"body requests settled" [[LeiosFetchRequest] -> String
forall {t :: * -> *} {a}. Foldable t => t a -> String
bucket ((LeiosFetchRequest -> Bool)
-> [LeiosFetchRequest] -> [LeiosFetchRequest]
forall a. (a -> Bool) -> [a] -> [a]
filter LeiosFetchRequest -> Bool
isBodyRequest [LeiosFetchRequest]
settled)] (Property -> Property) -> Property -> Property
forall a b. (a -> b) -> a -> b
$
            String -> [String] -> Property -> Property
forall prop.
Testable prop =>
String -> [String] -> prop -> Property
tabulate String
"txs requests settled" [[LeiosFetchRequest] -> String
forall {t :: * -> *} {a}. Foldable t => t a -> String
bucket ((LeiosFetchRequest -> Bool)
-> [LeiosFetchRequest] -> [LeiosFetchRequest]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool)
-> (LeiosFetchRequest -> Bool) -> LeiosFetchRequest -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LeiosFetchRequest -> Bool
isBodyRequest) [LeiosFetchRequest]
settled)] (Property -> Property) -> Property -> Property
forall a b. (a -> b) -> a -> b
$
              case [(Int
n, [String]
vs) | (Int
n, Sim
sim) <- [Int] -> [Sim] -> [(Int, Sim)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 :: Int ..] [Sim]
sims, let vs :: [String]
vs = Sim -> [String]
violations Sim
sim, Bool -> Bool
not ([String] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [String]
vs)] of
                [] -> Bool -> Property
forall prop. Testable prop => prop -> Property
property Bool
True
                (Int
n, [String]
vs) : [(Int, [String])]
_ -> String -> Bool -> Property
forall prop. Testable prop => String -> prop -> Property
counterexample ([String] -> String
unlines ((String
"after " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Int -> String
forall a. Show a => a -> String
show Int
n String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" steps:") String -> [String] -> [String]
forall a. a -> [a] -> [a]
: [String]
vs)) Bool
False
 where
  bucket :: t a -> String
bucket t a
reqs = case t a -> Int
forall a. t a -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length t a
reqs of
    Int
0 -> String
"none"
    Int
n
      | Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
10 -> String
"fewer than 10"
      | Bool
otherwise -> String
"10 or more"

-- | The peers, the endorser blocks they offer, and what the closures lack.
data Setup = MkSetup
  { Setup -> Int
setupSeed :: !Int
  , Setup -> Map Int (Map LeiosPoint PeerOffer)
setupOffers :: !(Map.Map Peer (Map.Map LeiosPoint PeerOffer))
  , Setup -> Map LeiosPoint (IntMap (TxHash, Word32))
setupMisses :: !(Map.Map LeiosPoint (IntMap.IntMap (TxHash, BytesSize)))
  -- ^ The transactions each point lacks once its body is held
  }
  deriving Int -> Setup -> String -> String
[Setup] -> String -> String
Setup -> String
(Int -> Setup -> String -> String)
-> (Setup -> String) -> ([Setup] -> String -> String) -> Show Setup
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> Setup -> String -> String
showsPrec :: Int -> Setup -> String -> String
$cshow :: Setup -> String
show :: Setup -> String
$cshowList :: [Setup] -> String -> String
showList :: [Setup] -> String -> String
Show

-- | One step of the decision loop or of what settles its requests.
data Step
  = -- | Decide, and send the requests.
    Decide
  | -- | One of the body requests in flight is answered, and its write settles.
    BodyReply Int
  | -- | One of the txs requests in flight is answered, and its write settles.
    TxsReply Int
  | -- | A peer disconnects.
    Disconnect Int
  | -- | A request of a disconnected peer settles.
    LateReply Int
  | -- | The immutable tip reaches this slot.
    Prune Word64
  deriving Int -> Step -> String -> String
[Step] -> String -> String
Step -> String
(Int -> Step -> String -> String)
-> (Step -> String) -> ([Step] -> String -> String) -> Show Step
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> Step -> String -> String
showsPrec :: Int -> Step -> String -> String
$cshow :: Step -> String
show :: Step -> String
$cshowList :: [Step] -> String -> String
showList :: [Step] -> String -> String
Show

data Sim = MkSim
  { Sim -> LeiosOutstanding Int
simOutstanding :: !(LeiosOutstanding Peer)
  , Sim -> Map Int (Map LeiosPoint PeerOffer)
simOffers :: !(Map.Map Peer (Map.Map LeiosPoint PeerOffer))
  -- ^ The offers of each connected peer
  , Sim -> Map Int [LeiosFetchRequest]
simInFlight :: !(Map.Map Peer [LeiosFetchRequest])
  -- ^ The requests in flight from each connected peer
  , Sim -> [(Int, LeiosFetchRequest)]
simLate :: ![(Peer, LeiosFetchRequest)]
  -- ^ The requests that were in flight when their peer disconnected
  , Sim -> [(Int, LeiosFetchRequest)]
simSettled :: ![(Peer, LeiosFetchRequest)]
  -- ^ What the last step settled
  }

-- | Small enough that the per-peer budgets and the job and request sizes bind.
propEnv :: LeiosFetchStaticEnv
propEnv :: LeiosFetchStaticEnv
propEnv =
  MkLeiosFetchStaticEnv
    { maxRequestedBytesSizePerPeer :: Word32
maxRequestedBytesSizePerPeer = Word32
3000
    , maxRequestedBytesSizePerBigLedgerPeer :: Word32
maxRequestedBytesSizePerBigLedgerPeer = Word32
6000
    , maxRequestBytesSize :: Word32
maxRequestBytesSize = Word32
1000
    , maxJobBytesSize :: Word32
maxJobBytesSize = Word32
500
    , maxJobTxCount :: Int
maxJobTxCount = Int
4
    }

propPeers :: [Peer]
propPeers :: [Int]
propPeers = [Int
0, Int
1, Int
2]

propBigLedgerPeers :: Map.Map Peer IsBigLedgerPeer
propBigLedgerPeers :: Map Int IsBigLedgerPeer
propBigLedgerPeers = Int -> IsBigLedgerPeer -> Map Int IsBigLedgerPeer
forall k a. k -> a -> Map k a
Map.singleton Int
2 IsBigLedgerPeer
IsBigLedgerPeer

-- | Each in its own slot, so each is its own election's.
propPoints :: [LeiosPoint]
propPoints :: [LeiosPoint]
propPoints = (Word -> Char -> LeiosPoint) -> [Word] -> String -> [LeiosPoint]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Word -> Char -> LeiosPoint
point [Word
1 ..] String
"abcdef"

genSetup :: Gen Setup
genSetup :: Gen Setup
genSetup =
  Int
-> Map Int (Map LeiosPoint PeerOffer)
-> Map LeiosPoint (IntMap (TxHash, Word32))
-> Setup
MkSetup
    (Int
 -> Map Int (Map LeiosPoint PeerOffer)
 -> Map LeiosPoint (IntMap (TxHash, Word32))
 -> Setup)
-> Gen Int
-> Gen
     (Map Int (Map LeiosPoint PeerOffer)
      -> Map LeiosPoint (IntMap (TxHash, Word32)) -> Setup)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Gen Int
forall a. Arbitrary a => Gen a
arbitrary
    Gen
  (Map Int (Map LeiosPoint PeerOffer)
   -> Map LeiosPoint (IntMap (TxHash, Word32)) -> Setup)
-> Gen (Map Int (Map LeiosPoint PeerOffer))
-> Gen (Map LeiosPoint (IntMap (TxHash, Word32)) -> Setup)
forall a b. Gen (a -> b) -> Gen a -> Gen b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> ([(Int, Map LeiosPoint PeerOffer)]
-> Map Int (Map LeiosPoint PeerOffer)
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList ([(Int, Map LeiosPoint PeerOffer)]
 -> Map Int (Map LeiosPoint PeerOffer))
-> Gen [(Int, Map LeiosPoint PeerOffer)]
-> Gen (Map Int (Map LeiosPoint PeerOffer))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Int -> Gen (Int, Map LeiosPoint PeerOffer))
-> [Int] -> Gen [(Int, Map LeiosPoint PeerOffer)]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (\Int
peer -> (,) Int
peer (Map LeiosPoint PeerOffer -> (Int, Map LeiosPoint PeerOffer))
-> Gen (Map LeiosPoint PeerOffer)
-> Gen (Int, Map LeiosPoint PeerOffer)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Gen (Map LeiosPoint PeerOffer)
genOffers) [Int]
propPeers)
    Gen (Map LeiosPoint (IntMap (TxHash, Word32)) -> Setup)
-> Gen (Map LeiosPoint (IntMap (TxHash, Word32))) -> Gen Setup
forall a b. Gen (a -> b) -> Gen a -> Gen b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> ([(LeiosPoint, IntMap (TxHash, Word32))]
-> Map LeiosPoint (IntMap (TxHash, Word32))
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList ([(LeiosPoint, IntMap (TxHash, Word32))]
 -> Map LeiosPoint (IntMap (TxHash, Word32)))
-> Gen [(LeiosPoint, IntMap (TxHash, Word32))]
-> Gen (Map LeiosPoint (IntMap (TxHash, Word32)))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (LeiosPoint -> Gen (LeiosPoint, IntMap (TxHash, Word32)))
-> [LeiosPoint] -> Gen [(LeiosPoint, IntMap (TxHash, Word32))]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (\LeiosPoint
p -> (,) LeiosPoint
p (IntMap (TxHash, Word32) -> (LeiosPoint, IntMap (TxHash, Word32)))
-> Gen (IntMap (TxHash, Word32))
-> Gen (LeiosPoint, IntMap (TxHash, Word32))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Gen (IntMap (TxHash, Word32))
genMisses) [LeiosPoint]
propPoints)
 where
  genOffers :: Gen (Map LeiosPoint PeerOffer)
genOffers = do
    points <- [LeiosPoint] -> Gen [LeiosPoint]
forall a. [a] -> Gen [a]
sublistOf [LeiosPoint]
propPoints
    Map.fromList <$> traverse (\LeiosPoint
p -> (,) LeiosPoint
p (PeerOffer -> (LeiosPoint, PeerOffer))
-> (OfferedHalves -> PeerOffer)
-> OfferedHalves
-> (LeiosPoint, PeerOffer)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. StrictMaybe (LeiosEbByteSizes 'SizeLimit)
-> OfferedHalves -> PeerOffer
MkPeerOffer StrictMaybe (LeiosEbByteSizes 'SizeLimit)
forall a. StrictMaybe a
SNothing (OfferedHalves -> (LeiosPoint, PeerOffer))
-> Gen OfferedHalves -> Gen (LeiosPoint, PeerOffer)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Gen OfferedHalves
genHalves) points
  genHalves :: Gen OfferedHalves
genHalves =
    [(Int, Gen OfferedHalves)] -> Gen OfferedHalves
forall a. HasCallStack => [(Int, Gen a)] -> Gen a
frequency
      [ (Int
1, Word32 -> OfferedHalves
OfferedBody (Word32 -> OfferedHalves) -> Gen Word32 -> Gen OfferedHalves
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Word32, Word32) -> Gen Word32
forall a. Random a => (a, a) -> Gen a
choose (Word32
100, Word32
2000))
      , (Int
1, OfferedHalves -> Gen OfferedHalves
forall a. a -> Gen a
forall (f :: * -> *) a. Applicative f => a -> f a
pure OfferedHalves
OfferedClosure)
      , (Int
3, Word32 -> OfferedHalves
OfferedBodyAndClosure (Word32 -> OfferedHalves) -> Gen Word32 -> Gen OfferedHalves
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Word32, Word32) -> Gen Word32
forall a. Random a => (a, a) -> Gen a
choose (Word32
100, Word32
2000))
      ]
  genMisses :: Gen (IntMap (TxHash, Word32))
genMisses = do
    n <- (Int, Int) -> Gen Int
forall a. Random a => (a, a) -> Gen a
choose (Int
1, Int
12)
    sizes <- vectorOf n (choose (50, 400))
    pure $ IntMap.fromList [(off, (txHashOf off, sz)) | (off, sz) <- zip [0 ..] sizes]

genStep :: Gen Step
genStep :: Gen Step
genStep =
  [(Int, Gen Step)] -> Gen Step
forall a. HasCallStack => [(Int, Gen a)] -> Gen a
frequency
    [ (Int
10, Step -> Gen Step
forall a. a -> Gen a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Step
Decide)
    , (Int
8, Int -> Step
BodyReply (Int -> Step) -> Gen Int -> Gen Step
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Gen Int
forall a. Arbitrary a => Gen a
arbitrary)
    , (Int
8, Int -> Step
TxsReply (Int -> Step) -> Gen Int -> Gen Step
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Gen Int
forall a. Arbitrary a => Gen a
arbitrary)
    , (Int
1, Int -> Step
Disconnect (Int -> Step) -> Gen Int -> Gen Step
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Gen Int
forall a. Arbitrary a => Gen a
arbitrary)
    , (Int
1, Int -> Step
LateReply (Int -> Step) -> Gen Int -> Gen Step
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Gen Int
forall a. Arbitrary a => Gen a
arbitrary)
    , -- Never past the last two points.
      (Int
1, Word64 -> Step
Prune (Word64 -> Step) -> Gen Word64 -> Gen Step
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Word64, Word64) -> Gen Word64
forall a. Random a => (a, a) -> Gen a
choose (Word64
0, Word64
5))
    ]

-- | Every point announced, each focusing its own election.
initialSim :: Setup -> Sim
initialSim :: Setup -> Sim
initialSim Setup
setup =
  MkSim
    { simOutstanding :: LeiosOutstanding Int
simOutstanding =
        (LeiosOutstanding Int -> LeiosPoint -> LeiosOutstanding Int)
-> LeiosOutstanding Int -> [LeiosPoint] -> LeiosOutstanding Int
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
F.foldl' ((LeiosPoint -> LeiosOutstanding Int -> LeiosOutstanding Int)
-> LeiosOutstanding Int -> LeiosPoint -> LeiosOutstanding Int
forall a b c. (a -> b -> c) -> b -> a -> c
flip LeiosPoint -> LeiosOutstanding Int -> LeiosOutstanding Int
forall {peer}.
LeiosPoint -> LeiosOutstanding peer -> LeiosOutstanding peer
announce) (StdGen -> SlotNo -> LeiosOutstanding Int
forall peer. StdGen -> SlotNo -> LeiosOutstanding peer
emptyLeiosOutstanding (Int -> StdGen
mkStdGen (Setup -> Int
setupSeed Setup
setup)) (Word64 -> SlotNo
SlotNo Word64
0)) [LeiosPoint]
propPoints
    , simOffers :: Map Int (Map LeiosPoint PeerOffer)
simOffers = Setup -> Map Int (Map LeiosPoint PeerOffer)
setupOffers Setup
setup
    , simInFlight :: Map Int [LeiosFetchRequest]
simInFlight = Map Int [LeiosFetchRequest]
forall k a. Map k a
Map.empty
    , simLate :: [(Int, LeiosFetchRequest)]
simLate = []
    , simSettled :: [(Int, LeiosFetchRequest)]
simSettled = []
    }
 where
  announce :: LeiosPoint -> LeiosOutstanding peer -> LeiosOutstanding peer
announce p :: LeiosPoint
p@(MkLeiosPoint SlotNo
slot EndorserBlockHash
ebHash) =
    ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
focusElectionIfUnfocused (SlotNo -> KeyHash BlockIssuer -> ElectionId
ElectionId SlotNo
slot KeyHash BlockIssuer
forall (r :: KeyRole). KeyHash r
fixtureElectee) EndorserBlockHash
ebHash
      (LeiosOutstanding peer -> LeiosOutstanding peer)
-> (LeiosOutstanding peer -> LeiosOutstanding peer)
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding peer
-> LeiosOutstanding peer
recordReferencedPoint LeiosPoint
p StrictMaybe RelativeTime
forall a. StrictMaybe a
SNothing

simulate :: Setup -> Sim -> Step -> Sim
simulate :: Setup -> Sim -> Step -> Sim
simulate Setup
setup Sim
sim0 = \case
  Step
Decide ->
    let (LeiosOutstanding Int
outstanding', Map Int (NESeq LeiosFetchRequest)
reqs, Map Int (NEMap LeiosPoint OfferPrune)
prunes) =
          LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map Int (Map LeiosPoint PeerOffer)
-> Map Int IsBigLedgerPeer
-> LeiosOutstanding Int
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
forall peer.
Ord peer =>
LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map peer (Map LeiosPoint PeerOffer)
-> Map peer IsBigLedgerPeer
-> LeiosOutstanding peer
-> (LeiosOutstanding peer, Map peer (NESeq LeiosFetchRequest),
    Map peer (NEMap LeiosPoint OfferPrune))
leiosFetchLogicIteration
            LeiosFetchStaticEnv
propEnv
            SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
anyBounds
            ((SlotNo, Word64) -> Maybe (SlotNo, Word64)
forall a. a -> Maybe a
Just (Word64 -> SlotNo
SlotNo Word64
0, Word64
priorityWindow))
            (Sim -> Map Int (Map LeiosPoint PeerOffer)
simOffers Sim
sim)
            Map Int IsBigLedgerPeer
propBigLedgerPeers
            (Sim -> LeiosOutstanding Int
simOutstanding Sim
sim)
     in Sim
sim
          { simOutstanding = outstanding'
          , simInFlight = Map.unionWith (<>) (simInFlight sim) (Map.map toList reqs)
          , simOffers =
              Map.mapWithKey
                (\Int
peer -> Map LeiosPoint OfferPrune
-> Map LeiosPoint PeerOffer -> Map LeiosPoint PeerOffer
pruneOffers (Map LeiosPoint OfferPrune
-> (NEMap LeiosPoint OfferPrune -> Map LeiosPoint OfferPrune)
-> Maybe (NEMap LeiosPoint OfferPrune)
-> Map LeiosPoint OfferPrune
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Map LeiosPoint OfferPrune
forall k a. Map k a
Map.empty NEMap LeiosPoint OfferPrune -> Map LeiosPoint OfferPrune
forall k a. NEMap k a -> Map k a
NEMap.toMap (Int
-> Map Int (NEMap LeiosPoint OfferPrune)
-> Maybe (NEMap LeiosPoint OfferPrune)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Int
peer Map Int (NEMap LeiosPoint OfferPrune)
prunes)))
                (simOffers sim)
          }
  BodyReply Int
i -> Int -> (LeiosFetchRequest -> Bool) -> Sim
reply Int
i LeiosFetchRequest -> Bool
isBodyRequest
  TxsReply Int
i -> Int -> (LeiosFetchRequest -> Bool) -> Sim
reply Int
i (Bool -> Bool
not (Bool -> Bool)
-> (LeiosFetchRequest -> Bool) -> LeiosFetchRequest -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LeiosFetchRequest -> Bool
isBodyRequest)
  Disconnect Int
i -> case Int -> [Int] -> Maybe (Int, [Int])
forall a. Int -> [a] -> Maybe (a, [a])
pickIndex Int
i (Map Int (Map LeiosPoint PeerOffer) -> [Int]
forall k a. Map k a -> [k]
Map.keys (Sim -> Map Int (Map LeiosPoint PeerOffer)
simOffers Sim
sim)) of
    Maybe (Int, [Int])
Nothing -> Sim
sim
    Just (Int
peer, [Int]
_rest) ->
      Sim
sim
        { simOutstanding = removePeerFromOutstanding peer (simOutstanding sim)
        , simOffers = Map.delete peer (simOffers sim)
        , simInFlight = Map.delete peer (simInFlight sim)
        , simLate = [(peer, req) | req <- Map.findWithDefault [] peer (simInFlight sim)] <> simLate sim
        }
  LateReply Int
i -> case Int
-> [(Int, LeiosFetchRequest)]
-> Maybe ((Int, LeiosFetchRequest), [(Int, LeiosFetchRequest)])
forall a. Int -> [a] -> Maybe (a, [a])
pickIndex Int
i (Sim -> [(Int, LeiosFetchRequest)]
simLate Sim
sim) of
    Maybe ((Int, LeiosFetchRequest), [(Int, LeiosFetchRequest)])
Nothing -> Sim
sim
    Just ((Int
peer, LeiosFetchRequest
req), [(Int, LeiosFetchRequest)]
rest) -> Int -> LeiosFetchRequest -> Sim -> Sim
settle Int
peer LeiosFetchRequest
req Sim
sim{simLate = rest}
  Prune Word64
slot -> Sim
sim{simOutstanding = pruneOutstandingToImmTip (SlotNo slot) (simOutstanding sim)}
 where
  sim :: Sim
sim = Sim
sim0{simSettled = []}

  reply :: Int -> (LeiosFetchRequest -> Bool) -> Sim
reply Int
i LeiosFetchRequest -> Bool
isKind =
    case Int -> [(Int, Int)] -> Maybe ((Int, Int), [(Int, Int)])
forall a. Int -> [a] -> Maybe (a, [a])
pickIndex
      Int
i
      [ (Int
peer, Int
k)
      | (Int
peer, [LeiosFetchRequest]
reqs) <- Map Int [LeiosFetchRequest] -> [(Int, [LeiosFetchRequest])]
forall k a. Map k a -> [(k, a)]
Map.toList (Sim -> Map Int [LeiosFetchRequest]
simInFlight Sim
sim)
      , (Int
k, LeiosFetchRequest
req) <- [Int] -> [LeiosFetchRequest] -> [(Int, LeiosFetchRequest)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] [LeiosFetchRequest]
reqs
      , LeiosFetchRequest -> Bool
isKind LeiosFetchRequest
req
      ] of
      Maybe ((Int, Int), [(Int, Int)])
Nothing -> Sim
sim
      Just ((Int
peer, Int
k), [(Int, Int)]
_rest) -> case Int
-> [LeiosFetchRequest]
-> Maybe (LeiosFetchRequest, [LeiosFetchRequest])
forall a. Int -> [a] -> Maybe (a, [a])
pickIndex Int
k ([LeiosFetchRequest]
-> Int -> Map Int [LeiosFetchRequest] -> [LeiosFetchRequest]
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault [] Int
peer (Sim -> Map Int [LeiosFetchRequest]
simInFlight Sim
sim)) of
        Maybe (LeiosFetchRequest, [LeiosFetchRequest])
Nothing -> Sim
sim
        Just (LeiosFetchRequest
req, [LeiosFetchRequest]
rest) -> Int -> LeiosFetchRequest -> Sim -> Sim
settle Int
peer LeiosFetchRequest
req Sim
sim{simInFlight = Map.insert peer rest (simInFlight sim)}

  -- As the reply handlers do: refund on arrival, then record what the write
  -- settled.
  settle :: Int -> LeiosFetchRequest -> Sim -> Sim
settle Int
peer LeiosFetchRequest
req Sim
s =
    Sim
s
      { simOutstanding = case req of
          LeiosBlockRequest LeiosBlockRequest
r ->
            LeiosPoint
-> LeiosJobPool -> LeiosOutstanding Int -> LeiosOutstanding Int
forall peer.
LeiosPoint
-> LeiosJobPool -> LeiosOutstanding peer -> LeiosOutstanding peer
acquireEbBody
              LeiosBlockRequest
r.lbrPoint
              (LeiosFetchStaticEnv -> IntMap (TxHash, Word32) -> LeiosJobPool
newLeiosJobPool LeiosFetchStaticEnv
propEnv (IntMap (TxHash, Word32)
-> LeiosPoint
-> Map LeiosPoint (IntMap (TxHash, Word32))
-> IntMap (TxHash, Word32)
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault IntMap (TxHash, Word32)
forall a. IntMap a
IntMap.empty LeiosBlockRequest
r.lbrPoint (Setup -> Map LeiosPoint (IntMap (TxHash, Word32))
setupMisses Setup
setup)))
              (Int
-> LeiosPoint
-> Word32
-> LeiosOutstanding Int
-> LeiosOutstanding Int
forall peer.
Ord peer =>
peer
-> LeiosPoint
-> Word32
-> LeiosOutstanding peer
-> LeiosOutstanding peer
refundEbRequest Int
peer LeiosBlockRequest
r.lbrPoint LeiosBlockRequest
r.lbrOfferedSize (Sim -> LeiosOutstanding Int
simOutstanding Sim
s))
          LeiosBlockTxsRequest LeiosBlockTxsRequest
r ->
            Int
-> LeiosBlockTxsRequest
-> LeiosOutstanding Int
-> LeiosOutstanding Int
forall peer.
Ord peer =>
peer
-> LeiosBlockTxsRequest
-> LeiosOutstanding peer
-> LeiosOutstanding peer
completeTxRequest Int
peer LeiosBlockTxsRequest
r (Int -> Word32 -> LeiosOutstanding Int -> LeiosOutstanding Int
forall peer.
Ord peer =>
peer -> Word32 -> LeiosOutstanding peer -> LeiosOutstanding peer
refundTxRequest Int
peer (LeiosFetchRequest -> Word32
requestBytes LeiosFetchRequest
req) (Sim -> LeiosOutstanding Int
simOutstanding Sim
s))
      , simSettled = (peer, req) : simSettled s
      }

isBodyRequest :: LeiosFetchRequest -> Bool
isBodyRequest :: LeiosFetchRequest -> Bool
isBodyRequest = \case
  LeiosBlockRequest{} -> Bool
True
  LeiosBlockTxsRequest{} -> Bool
False

-- | The bytes a request was charged to its peer's budget.
requestBytes :: LeiosFetchRequest -> BytesSize
requestBytes :: LeiosFetchRequest -> Word32
requestBytes = \case
  LeiosBlockRequest LeiosBlockRequest
r -> LeiosBlockRequest
r.lbrOfferedSize
  LeiosBlockTxsRequest (MkLeiosBlockTxsRequest LeiosPoint
_point NEIntMap LeiosJob
jobs) ->
    [Word32] -> Word32
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Word32
bytes | Jobs.MkLeiosJob IntSet
_offsets Word32
bytes JobCommitment
_commitment <- NEIntMap LeiosJob -> [LeiosJob]
forall a. NEIntMap a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList NEIntMap LeiosJob
jobs]

-- | The element at this index, modulo the list's length, and the others.
pickIndex :: Int -> [a] -> Maybe (a, [a])
pickIndex :: forall a. Int -> [a] -> Maybe (a, [a])
pickIndex Int
i [a]
xs = Int -> [a] -> Maybe (a, [a])
forall {t} {a}. (Eq t, Num t) => t -> [a] -> Maybe (a, [a])
go (Int
i Int -> Int -> Int
forall a. Integral a => a -> a -> a
`mod` Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
1 ([a] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [a]
xs)) [a]
xs
 where
  go :: t -> [a] -> Maybe (a, [a])
go t
_ [] = Maybe (a, [a])
forall a. Maybe a
Nothing
  go t
0 (a
x : [a]
rest) = (a, [a]) -> Maybe (a, [a])
forall a. a -> Maybe a
Just (a
x, [a]
rest)
  go t
n (a
x : [a]
rest) = ([a] -> [a]) -> (a, [a]) -> (a, [a])
forall a b. (a -> b) -> (a, a) -> (a, b)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (a
x a -> [a] -> [a]
forall a. a -> [a] -> [a]
:) ((a, [a]) -> (a, [a])) -> Maybe (a, [a]) -> Maybe (a, [a])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> t -> [a] -> Maybe (a, [a])
go (t
n t -> t -> t
forall a. Num a => a -> a -> a
- t
1) [a]
rest

-- | How the outstanding state disagrees with the requests in flight.
violations :: Sim -> [String]
violations :: Sim -> [String]
violations Sim
sim =
  (Int -> [String]) -> [Int] -> [String]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Int -> [String]
peerViolations [Int]
propPeers
    [String] -> [String] -> [String]
forall a. Semigroup a => a -> a -> a
<> [ String
"requestedEbPeers is not the inverse of requestedEbsPerPeer"
       | LeiosOutstanding Int -> Map LeiosPoint (Set Int)
forall peer. LeiosOutstanding peer -> Map LeiosPoint (Set peer)
requestedEbPeers LeiosOutstanding Int
o
           Map LeiosPoint (Set Int) -> Map LeiosPoint (Set Int) -> Bool
forall a. Eq a => a -> a -> Bool
/= (Set Int -> Set Int -> Set Int)
-> [(LeiosPoint, Set Int)] -> Map LeiosPoint (Set Int)
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
Map.fromListWith
             Set Int -> Set Int -> Set Int
forall a. Ord a => Set a -> Set a -> Set a
Set.union
             [(LeiosPoint
p, Int -> Set Int
forall a. a -> Set a
Set.singleton Int
peer) | (Int
peer, NESet LeiosPoint
ps) <- Map Int (NESet LeiosPoint) -> [(Int, NESet LeiosPoint)]
forall k a. Map k a -> [(k, a)]
Map.toList (LeiosOutstanding Int -> Map Int (NESet LeiosPoint)
forall peer. LeiosOutstanding peer -> Map peer (NESet LeiosPoint)
requestedEbsPerPeer LeiosOutstanding Int
o), LeiosPoint
p <- NESet LeiosPoint -> [LeiosPoint]
forall a. NESet a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList NESet LeiosPoint
ps]
       ]
    [String] -> [String] -> [String]
forall a. Semigroup a => a -> a -> a
<> ((LeiosPoint, EbState) -> [String])
-> [(LeiosPoint, EbState)] -> [String]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (LeiosPoint, EbState) -> [String]
poolViolations (Map LeiosPoint EbState -> [(LeiosPoint, EbState)]
forall k a. Map k a -> [(k, a)]
Map.toList (LeiosOutstanding Int -> Map LeiosPoint EbState
forall peer. LeiosOutstanding peer -> Map LeiosPoint EbState
ebState LeiosOutstanding Int
o))
 where
  o :: LeiosOutstanding Int
o = Sim -> LeiosOutstanding Int
simOutstanding Sim
sim
  inFlight :: Int -> [LeiosFetchRequest]
inFlight Int
peer = [LeiosFetchRequest]
-> Int -> Map Int [LeiosFetchRequest] -> [LeiosFetchRequest]
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault [] Int
peer (Sim -> Map Int [LeiosFetchRequest]
simInFlight Sim
sim)
  jobsHeld :: Int -> Map LeiosPoint IntSet
jobsHeld Int
peer =
    (NEIntSet -> IntSet)
-> Map LeiosPoint NEIntSet -> Map LeiosPoint IntSet
forall a b k. (a -> b) -> Map k a -> Map k b
Map.map NEIntSet -> IntSet
NEIntSet.toSet (Map LeiosPoint NEIntSet
-> Int
-> Map Int (Map LeiosPoint NEIntSet)
-> Map LeiosPoint NEIntSet
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault Map LeiosPoint NEIntSet
forall k a. Map k a
Map.empty Int
peer (LeiosOutstanding Int -> Map Int (Map LeiosPoint NEIntSet)
forall peer.
LeiosOutstanding peer -> Map peer (Map LeiosPoint NEIntSet)
requestedJobsPerPeer LeiosOutstanding Int
o))

  peerViolations :: Int -> [String]
peerViolations Int
peer =
    [ String
"peer " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Int -> String
forall a. Show a => a -> String
show Int
peer String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" is charged " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Word32 -> String
forall a. Show a => a -> String
show Word32
charged String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" bytes for " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Word32 -> String
forall a. Show a => a -> String
show Word32
owed String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" in flight"
    | let charged :: Word32
charged = Word32 -> Int -> Map Int Word32 -> Word32
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault Word32
0 Int
peer (LeiosOutstanding Int -> Map Int Word32
forall peer. LeiosOutstanding peer -> Map peer Word32
requestedBytesSizePerPeer LeiosOutstanding Int
o)
          owed :: Word32
owed = [Word32] -> Word32
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum ((LeiosFetchRequest -> Word32) -> [LeiosFetchRequest] -> [Word32]
forall a b. (a -> b) -> [a] -> [b]
map LeiosFetchRequest -> Word32
requestBytes (Int -> [LeiosFetchRequest]
inFlight Int
peer))
    , Word32
charged Word32 -> Word32 -> Bool
forall a. Eq a => a -> a -> Bool
/= Word32
owed
    ]
      [String] -> [String] -> [String]
forall a. Semigroup a => a -> a -> a
<> [ String
"peer " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Int -> String
forall a. Show a => a -> String
show Int
peer String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" is charged past its cap"
         | LeiosFetchStaticEnv
-> IsBigLedgerPeer -> LeiosOutstanding Int -> Int -> Int
forall peer.
Ord peer =>
LeiosFetchStaticEnv
-> IsBigLedgerPeer -> LeiosOutstanding peer -> peer -> Int
peerBudget LeiosFetchStaticEnv
propEnv (IsBigLedgerPeer
-> Int -> Map Int IsBigLedgerPeer -> IsBigLedgerPeer
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault IsBigLedgerPeer
IsNotBigLedgerPeer Int
peer Map Int IsBigLedgerPeer
propBigLedgerPeers) LeiosOutstanding Int
o Int
peer Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0
         ]
      [String] -> [String] -> [String]
forall a. Semigroup a => a -> a -> a
<> [ String
"peer "
             String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Int -> String
forall a. Show a => a -> String
show Int
peer
             String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" is tracked with bodies "
             String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Set LeiosPoint -> String
forall a. Show a => a -> String
show Set LeiosPoint
tracked
             String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" for "
             String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Set LeiosPoint -> String
forall a. Show a => a -> String
show Set LeiosPoint
bodies
             String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" in flight"
         | let tracked :: Set LeiosPoint
tracked = Set LeiosPoint
-> (NESet LeiosPoint -> Set LeiosPoint)
-> Maybe (NESet LeiosPoint)
-> Set LeiosPoint
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Set LeiosPoint
forall a. Set a
Set.empty NESet LeiosPoint -> Set LeiosPoint
forall a. NESet a -> Set a
NESet.toSet (Int -> Map Int (NESet LeiosPoint) -> Maybe (NESet LeiosPoint)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Int
peer (LeiosOutstanding Int -> Map Int (NESet LeiosPoint)
forall peer. LeiosOutstanding peer -> Map peer (NESet LeiosPoint)
requestedEbsPerPeer LeiosOutstanding Int
o))
               bodies :: Set LeiosPoint
bodies = [LeiosPoint] -> Set LeiosPoint
forall a. Ord a => [a] -> Set a
Set.fromList [LeiosBlockRequest
r.lbrPoint | LeiosBlockRequest LeiosBlockRequest
r <- Int -> [LeiosFetchRequest]
inFlight Int
peer]
         , Set LeiosPoint
tracked Set LeiosPoint -> Set LeiosPoint -> Bool
forall a. Eq a => a -> a -> Bool
/= Set LeiosPoint
bodies
         ]
      [String] -> [String] -> [String]
forall a. Semigroup a => a -> a -> a
<> [ String
"peer "
             String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Int -> String
forall a. Show a => a -> String
show Int
peer
             String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" is tracked with jobs "
             String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Map LeiosPoint IntSet -> String
forall a. Show a => a -> String
show Map LeiosPoint IntSet
tracked
             String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" for "
             String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Map LeiosPoint IntSet -> String
forall a. Show a => a -> String
show Map LeiosPoint IntSet
jobs
             String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" in flight"
         | let tracked :: Map LeiosPoint IntSet
tracked = Int -> Map LeiosPoint IntSet
jobsHeld Int
peer
               jobs :: Map LeiosPoint IntSet
jobs =
                 (IntSet -> IntSet -> IntSet)
-> [(LeiosPoint, IntSet)] -> Map LeiosPoint IntSet
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
Map.fromListWith
                   IntSet -> IntSet -> IntSet
IntSet.union
                   [ (LeiosPoint
p, NEIntSet -> IntSet
NEIntSet.toSet (NEIntMap LeiosJob -> NEIntSet
forall a. NEIntMap a -> NEIntSet
NEIntMap.keysSet NEIntMap LeiosJob
js))
                   | LeiosBlockTxsRequest (MkLeiosBlockTxsRequest LeiosPoint
p NEIntMap LeiosJob
js) <- Int -> [LeiosFetchRequest]
inFlight Int
peer
                   ]
         , Map LeiosPoint IntSet
tracked Map LeiosPoint IntSet -> Map LeiosPoint IntSet -> Bool
forall a. Eq a => a -> a -> Bool
/= Map LeiosPoint IntSet
jobs
         ]

  poolViolations :: (LeiosPoint, EbState) -> [String]
poolViolations (LeiosPoint
p, MkEbState StrictMaybe RelativeTime
_onset EbFetchState
fetchState) = case EbFetchState
fetchState of
    EbFetchState
NoBody -> []
    BodyAcquired LeiosJobPool
pool ->
      [LeiosPoint -> String
forall a. Show a => a -> String
show LeiosPoint
p String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
"'s job pool has an inexact reverse index" | Bool -> Bool
not (LeiosJobPool -> Bool
Jobs.hasExactReverseIndex LeiosJobPool
pool)]
        [String] -> [String] -> [String]
forall a. Semigroup a => a -> a -> a
<> [ LeiosPoint -> String
forall a. Show a => a -> String
show LeiosPoint
p
               String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
"'s job "
               String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Int -> String
forall a. Show a => a -> String
show Int
jid
               String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" counts "
               String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Int -> String
forall a. Show a => a -> String
show Int
m
               String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" requests for "
               String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Int -> String
forall a. Show a => a -> String
show Int
n
               String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" in flight"
           | (Int
jid, Int
m) <- IntMap Int -> [(Int, Int)]
forall a. IntMap a -> [(Int, a)]
IntMap.toList (LeiosJobPool -> IntMap Int
Jobs.jobMultiplicities LeiosJobPool
pool)
           , let n :: Int
n = [()] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [() | Int
peer <- [Int]
propPeers, Bool -> (IntSet -> Bool) -> Maybe IntSet -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (Int -> IntSet -> Bool
IntSet.member Int
jid) (LeiosPoint -> Map LeiosPoint IntSet -> Maybe IntSet
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup LeiosPoint
p (Int -> Map LeiosPoint IntSet
jobsHeld Int
peer))]
           , Int
m Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
n
           ]

{-------------------------------------------------------------------------------
  Scenario DSL
-------------------------------------------------------------------------------}

-- | A test fixture: peer offerings, outstanding work.
data Scenario = Scenario
  { Scenario -> Map Int (Set LeiosPoint)
scOfferings :: !(Map.Map Peer (Set.Set LeiosPoint))
  -- ^ The points each peer offers the body of.
  , Scenario -> Map LeiosPoint Word32
scOfferedSizes :: !(Map.Map LeiosPoint BytesSize)
  -- ^ The size each point is offered at.
  --
  -- NOTE a peculiarity of this harness: every peer offering a point offers it
  -- at the same size, the one 'withMissingBody' named. The protocol does not
  -- work that way --- each offer carries its own size, and the decision logic
  -- asks for whatever the peer it is asking claimed --- so no scenario here can
  -- have two peers disagree about a size. Nothing these tests cover turns on
  -- that.
  --
  -- It is a field of its own because the size is the offering peer's claim
  -- rather than anything the outstanding state holds, so the fixture must
  -- supply it.
  , Scenario -> LeiosOutstanding Int
scOutstanding :: !(LeiosOutstanding Peer)
  }

env :: LeiosFetchStaticEnv
env :: LeiosFetchStaticEnv
env = Word32 -> LeiosFetchStaticEnv
defaultLeiosFetchStaticEnv (Word32
60 Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
* Word32
1000 Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
* Word32
1000)

empty :: Scenario
empty :: Scenario
empty =
  Scenario
    { scOfferings :: Map Int (Set LeiosPoint)
scOfferings = Map Int (Set LeiosPoint)
forall k a. Map k a
Map.empty
    , scOfferedSizes :: Map LeiosPoint Word32
scOfferedSizes = Map LeiosPoint Word32
forall k a. Map k a
Map.empty
    , scOutstanding :: LeiosOutstanding Int
scOutstanding = StdGen -> SlotNo -> LeiosOutstanding Int
forall peer. StdGen -> SlotNo -> LeiosOutstanding peer
emptyLeiosOutstanding (Int -> StdGen
mkStdGen Int
0) (Word64 -> SlotNo
SlotNo Word64
0)
    }

-- | The body of this point is still to fetch, and every peer that offers it
-- offers it at this size.
withMissingBody :: LeiosPoint -> BytesSize -> Scenario -> Scenario
withMissingBody :: LeiosPoint -> Word32 -> Scenario -> Scenario
withMissingBody p :: LeiosPoint
p@(MkLeiosPoint SlotNo
slot EndorserBlockHash
ebHash) Word32
size Scenario
sc =
  (LeiosOutstanding Int -> LeiosOutstanding Int)
-> Scenario -> Scenario
onOutstanding LeiosOutstanding Int -> LeiosOutstanding Int
forall {peer}. LeiosOutstanding peer -> LeiosOutstanding peer
seed Scenario
sc{scOfferedSizes = Map.insert p size (scOfferedSizes sc)}
 where
  -- Seed what the announce path would: the 'ebState' NoBody entry the fetch
  -- loop drives bodies off of, and the election that is fetching it, without
  -- which the loop asks no one for it. Only a certificate overrules an election
  -- already fetching something, so this seeds it the way an announcement would.
  seed :: LeiosOutstanding peer -> LeiosOutstanding peer
seed =
    ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
focusElectionIfUnfocused (SlotNo -> KeyHash BlockIssuer -> ElectionId
ElectionId SlotNo
slot KeyHash BlockIssuer
forall (r :: KeyRole). KeyHash r
fixtureElectee) EndorserBlockHash
ebHash
      (LeiosOutstanding peer -> LeiosOutstanding peer)
-> (LeiosOutstanding peer -> LeiosOutstanding peer)
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding peer
-> LeiosOutstanding peer
recordReferencedPoint LeiosPoint
p StrictMaybe RelativeTime
forall a. StrictMaybe a
SNothing

-- | The one pool a scenario here pretends announced everything, since these
-- have no headers to take an issuer from. An endorser block's election is
-- therefore just its slot, so two announced in one slot share an election and
-- only the first is fetched.
fixtureElectee :: KeyHash r
fixtureElectee :: forall (r :: KeyRole). KeyHash r
fixtureElectee = Hash ADDRHASH (VerKeyDSIGN DSIGN) -> KeyHash r
forall (r :: KeyRole).
Hash ADDRHASH (VerKeyDSIGN DSIGN) -> KeyHash r
KeyHash (Hash ADDRHASH (VerKeyDSIGN DSIGN) -> KeyHash r)
-> Hash ADDRHASH (VerKeyDSIGN DSIGN) -> KeyHash r
forall a b. (a -> b) -> a -> b
$ ShortByteString -> Hash ADDRHASH (VerKeyDSIGN DSIGN)
forall h a.
(HashAlgorithm h, HasCallStack) =>
ShortByteString -> Hash h a
UnsafeHash (ShortByteString -> Hash ADDRHASH (VerKeyDSIGN DSIGN))
-> ShortByteString -> Hash ADDRHASH (VerKeyDSIGN DSIGN)
forall a b. (a -> b) -> a -> b
$ [Word8] -> ShortByteString
SBS.pack (Int -> Word8 -> [Word8]
forall a. Int -> a -> [a]
replicate Int
28 Word8
0)

alreadyRequestedEbFrom :: LeiosPoint -> [Peer] -> Scenario -> Scenario
alreadyRequestedEbFrom :: LeiosPoint -> [Int] -> Scenario -> Scenario
alreadyRequestedEbFrom LeiosPoint
p [Int]
peers =
  (LeiosOutstanding Int -> LeiosOutstanding Int)
-> Scenario -> Scenario
onOutstanding ((LeiosOutstanding Int -> LeiosOutstanding Int)
 -> Scenario -> Scenario)
-> (LeiosOutstanding Int -> LeiosOutstanding Int)
-> Scenario
-> Scenario
forall a b. (a -> b) -> a -> b
$ \LeiosOutstanding Int
o ->
    LeiosOutstanding Int
o
      { requestedEbPeers =
          Map.insertWith Set.union p (Set.fromList peers) (requestedEbPeers o)
      , requestedEbsPerPeer =
          foldr
            (\Int
peer -> (NESet LeiosPoint -> NESet LeiosPoint -> NESet LeiosPoint)
-> Int
-> NESet LeiosPoint
-> Map Int (NESet LeiosPoint)
-> Map Int (NESet LeiosPoint)
forall k a. Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
Map.insertWith NESet LeiosPoint -> NESet LeiosPoint -> NESet LeiosPoint
forall a. Ord a => NESet a -> NESet a -> NESet a
NESet.union Int
peer (LeiosPoint -> NESet LeiosPoint
forall a. a -> NESet a
NESet.singleton LeiosPoint
p))
            (requestedEbsPerPeer o)
            peers
      }

-- | Set a per-peer in-flight byte total. Use with the env's per-peer
-- cap to test the per-peer byte budget.
withRequestedBytesPerPeer :: Peer -> BytesSize -> Scenario -> Scenario
withRequestedBytesPerPeer :: Int -> Word32 -> Scenario -> Scenario
withRequestedBytesPerPeer Int
peer Word32
n =
  (LeiosOutstanding Int -> LeiosOutstanding Int)
-> Scenario -> Scenario
onOutstanding ((LeiosOutstanding Int -> LeiosOutstanding Int)
 -> Scenario -> Scenario)
-> (LeiosOutstanding Int -> LeiosOutstanding Int)
-> Scenario
-> Scenario
forall a b. (a -> b) -> a -> b
$ \LeiosOutstanding Int
o ->
    LeiosOutstanding Int
o{requestedBytesSizePerPeer = Map.insert peer n (requestedBytesSizePerPeer o)}

-- | The peer offers the body (only) of these points.
offersBody :: Peer -> [LeiosPoint] -> Scenario -> Scenario
offersBody :: Int -> [LeiosPoint] -> Scenario -> Scenario
offersBody Int
peer [LeiosPoint]
points Scenario
sc =
  Scenario
sc
    { scOfferings =
        Map.insertWith
          Set.union
          peer
          (Set.fromList points)
          (scOfferings sc)
    }

-- | Lift a function on 'LeiosOutstanding' to one on 'Scenario'.
onOutstanding :: (LeiosOutstanding Peer -> LeiosOutstanding Peer) -> Scenario -> Scenario
onOutstanding :: (LeiosOutstanding Int -> LeiosOutstanding Int)
-> Scenario -> Scenario
onOutstanding LeiosOutstanding Int -> LeiosOutstanding Int
f Scenario
sc = Scenario
sc{scOutstanding = f (scOutstanding sc)}

-- | Run the iteration and project the decisions.
runIteration :: Scenario -> Map.Map Peer (NESeq LeiosFetchRequest)
runIteration :: Scenario -> Map Int (NESeq LeiosFetchRequest)
runIteration =
  -- Any known current slot suffices here: these scenarios don't depend on the
  -- offer-visit order (the priority order is tested by 'test_fetchPriorityOrder').
  SlotNo -> Scenario -> Map Int (NESeq LeiosFetchRequest)
runIterationAt SlotNo
forall a. Bounded a => a
minBound

-- | Run the iteration at this current slot and project the decisions.
runIterationAt :: SlotNo -> Scenario -> Map.Map Peer (NESeq LeiosFetchRequest)
runIterationAt :: SlotNo -> Scenario -> Map Int (NESeq LeiosFetchRequest)
runIterationAt = (SlotNo
 -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> SlotNo -> Scenario -> Map Int (NESeq LeiosFetchRequest)
runIterationWithAt SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
anyBounds

-- | 'runIteration', with the ledger's bounds forecast thus.
runIterationWith ::
  (SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes SizeLimit)) ->
  Scenario ->
  Map.Map Peer (NESeq LeiosFetchRequest)
runIterationWith :: (SlotNo
 -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Scenario -> Map Int (NESeq LeiosFetchRequest)
runIterationWith SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
forecastEbBounds = (SlotNo
 -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> SlotNo -> Scenario -> Map Int (NESeq LeiosFetchRequest)
runIterationWithAt SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
forecastEbBounds SlotNo
forall a. Bounded a => a
minBound

-- | 'runIterationAt', with the ledger's bounds forecast thus.
runIterationWithAt ::
  (SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes SizeLimit)) ->
  SlotNo ->
  Scenario ->
  Map.Map Peer (NESeq LeiosFetchRequest)
runIterationWithAt :: (SlotNo
 -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> SlotNo -> Scenario -> Map Int (NESeq LeiosFetchRequest)
runIterationWithAt SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
forecastEbBounds SlotNo
currentSlot Scenario
sc =
  let (LeiosOutstanding Int
_out, Map Int (NESeq LeiosFetchRequest)
reqs, Map Int (NEMap LeiosPoint OfferPrune)
_drops) =
        -- No big-ledger peers in these scenarios.
        LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map Int (Map LeiosPoint PeerOffer)
-> Map Int IsBigLedgerPeer
-> LeiosOutstanding Int
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
forall peer.
Ord peer =>
LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map peer (Map LeiosPoint PeerOffer)
-> Map peer IsBigLedgerPeer
-> LeiosOutstanding peer
-> (LeiosOutstanding peer, Map peer (NESeq LeiosFetchRequest),
    Map peer (NEMap LeiosPoint OfferPrune))
leiosFetchLogicIteration
          LeiosFetchStaticEnv
env
          SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
forecastEbBounds
          ((SlotNo, Word64) -> Maybe (SlotNo, Word64)
forall a. a -> Maybe a
Just (SlotNo
currentSlot, Word64
priorityWindow))
          ((Set LeiosPoint -> Map LeiosPoint PeerOffer)
-> Map Int (Set LeiosPoint) -> Map Int (Map LeiosPoint PeerOffer)
forall a b k. (a -> b) -> Map k a -> Map k b
Map.map ((LeiosPoint -> PeerOffer)
-> Set LeiosPoint -> Map LeiosPoint PeerOffer
forall k a. (k -> a) -> Set k -> Map k a
Map.fromSet (Map LeiosPoint Word32 -> LeiosPoint -> PeerOffer
resolveOfferSize Scenario
sc.scOfferedSizes)) Scenario
sc.scOfferings)
          Map Int IsBigLedgerPeer
forall k a. Map k a
Map.empty
          Scenario
sc.scOutstanding
   in Map Int (NESeq LeiosFetchRequest)
reqs

-- | Give a fixture's body offer the size 'withMissingBody' said peers offer that
-- point at, which is the size the decision logic then requests. A point no
-- 'withMissingBody' named is offered at size 0, which matters to no scenario:
-- no election fetches it.
resolveOfferSize :: Map.Map LeiosPoint BytesSize -> LeiosPoint -> PeerOffer
resolveOfferSize :: Map LeiosPoint Word32 -> LeiosPoint -> PeerOffer
resolveOfferSize Map LeiosPoint Word32
sizes LeiosPoint
p = StrictMaybe (LeiosEbByteSizes 'SizeLimit)
-> OfferedHalves -> PeerOffer
MkPeerOffer StrictMaybe (LeiosEbByteSizes 'SizeLimit)
forall a. StrictMaybe a
SNothing (Word32 -> OfferedHalves
OfferedBody (Word32 -> LeiosPoint -> Map LeiosPoint Word32 -> Word32
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault Word32
0 LeiosPoint
p Map LeiosPoint Word32
sizes))

-- | How many slots before the current one a point is still worth voting on, in
-- these tests.
priorityWindow :: Word64
priorityWindow :: Word64
priorityWindow = Word64
10

{-------------------------------------------------------------------------------
  Assertions
-------------------------------------------------------------------------------}

assertBodyRequest ::
  Peer -> LeiosPoint -> BytesSize -> Map.Map Peer (NESeq LeiosFetchRequest) -> IO ()
assertBodyRequest :: Int
-> LeiosPoint
-> Word32
-> Map Int (NESeq LeiosFetchRequest)
-> Assertion
assertBodyRequest Int
peer LeiosPoint
p Word32
size Map Int (NESeq LeiosFetchRequest)
m =
  case Int
-> Map Int (NESeq LeiosFetchRequest)
-> Maybe (NESeq LeiosFetchRequest)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Int
peer Map Int (NESeq LeiosFetchRequest)
m of
    Maybe (NESeq LeiosFetchRequest)
Nothing -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure (String -> Assertion) -> String -> Assertion
forall a b. (a -> b) -> a -> b
$ String
"no request for peer " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Int -> String
forall a. Show a => a -> String
show Int
peer
    Just NESeq LeiosFetchRequest
reqs ->
      [ (LeiosPoint
pt.pointEbHash, Word32
sz)
      | LeiosBlockRequest (MkLeiosBlockRequest LeiosPoint
pt Word32
sz LeiosEbByteSizes 'SizeLimit
_) <- NESeq LeiosFetchRequest -> [LeiosFetchRequest]
forall a. NESeq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList NESeq LeiosFetchRequest
reqs
      ]
        [(EndorserBlockHash, Word32)]
-> [(EndorserBlockHash, Word32)] -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= [(LeiosPoint
p.pointEbHash, Word32
size)]

assertNoRequests :: Map.Map Peer (NESeq LeiosFetchRequest) -> IO ()
assertNoRequests :: Map Int (NESeq LeiosFetchRequest) -> Assertion
assertNoRequests Map Int (NESeq LeiosFetchRequest)
m = Map Int (NESeq LeiosFetchRequest) -> [Int]
forall k a. Map k a -> [k]
Map.keys Map Int (NESeq LeiosFetchRequest)
m [Int] -> [Int] -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= []

-- | Assert that requests target exactly the given set of peers (regardless of
-- what each request is).
assertRequestPeers :: [Peer] -> Map.Map Peer (NESeq LeiosFetchRequest) -> IO ()
assertRequestPeers :: [Int] -> Map Int (NESeq LeiosFetchRequest) -> Assertion
assertRequestPeers [Int]
expected Map Int (NESeq LeiosFetchRequest)
m = Map Int (NESeq LeiosFetchRequest) -> Set Int
forall k a. Map k a -> Set k
Map.keysSet Map Int (NESeq LeiosFetchRequest)
m Set Int -> Set Int -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= [Int] -> Set Int
forall a. Ord a => [a] -> Set a
Set.fromList [Int]
expected

-- | Assert how many distinct peers received a request.
assertRequestPeerCount :: Int -> Map.Map Peer (NESeq LeiosFetchRequest) -> IO ()
assertRequestPeerCount :: Int -> Map Int (NESeq LeiosFetchRequest) -> Assertion
assertRequestPeerCount Int
n Map Int (NESeq LeiosFetchRequest)
m = Map Int (NESeq LeiosFetchRequest) -> Int
forall k a. Map k a -> Int
Map.size Map Int (NESeq LeiosFetchRequest)
m Int -> Int -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= Int
n

{-------------------------------------------------------------------------------
  Fixture helpers
-------------------------------------------------------------------------------}

-- | A 'LeiosPoint' with a slot and an EB hash derived from a Char,
-- so tests read `point 1 'a'` instead of long byte literals.
point :: Word -> Char -> LeiosPoint
point :: Word -> Char -> LeiosPoint
point Word
slot Char
c = SlotNo -> EndorserBlockHash -> LeiosPoint
MkLeiosPoint (Word64 -> SlotNo
SlotNo (Word -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word
slot)) (Char -> EndorserBlockHash
eb Char
c)

-- | Every offset the requests ask a peer for.
requestedOffsets :: Map.Map Peer (NESeq LeiosFetchRequest) -> IntSet.IntSet
requestedOffsets :: Map Int (NESeq LeiosFetchRequest) -> IntSet
requestedOffsets Map Int (NESeq LeiosFetchRequest)
m =
  [IntSet] -> IntSet
forall (f :: * -> *). Foldable f => f IntSet -> IntSet
IntSet.unions
    [ IntSet
offs
    | NESeq LeiosFetchRequest
reqs <- Map Int (NESeq LeiosFetchRequest) -> [NESeq LeiosFetchRequest]
forall k a. Map k a -> [a]
Map.elems Map Int (NESeq LeiosFetchRequest)
m
    , LeiosBlockTxsRequest (MkLeiosBlockTxsRequest LeiosPoint
_ NEIntMap LeiosJob
jobs) <- NESeq LeiosFetchRequest -> [LeiosFetchRequest]
forall a. NESeq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList NESeq LeiosFetchRequest
reqs
    , Jobs.MkLeiosJob IntSet
offs Word32
_ JobCommitment
_ <- NEIntMap LeiosJob -> [LeiosJob]
forall a. NEIntMap a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList NEIntMap LeiosJob
jobs
    ]

-- | Distinct tx hash from an offset.
txHashOf :: Int -> TxHash
txHashOf :: Int -> TxHash
txHashOf Int
i = ShortByteString -> TxHash
forall h a.
(HashAlgorithm h, HasCallStack) =>
ShortByteString -> Hash h a
UnsafeHash (ShortByteString -> TxHash) -> ShortByteString -> TxHash
forall a b. (a -> b) -> a -> b
$ [Word8] -> ShortByteString
SBS.pack ([Word8] -> ShortByteString) -> [Word8] -> ShortByteString
forall a b. (a -> b) -> a -> b
$ Int -> Word8 -> [Word8]
forall a. Int -> a -> [a]
replicate Int
32 (Int -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
i)

-- | Distinct EB hash from a Char.
eb :: Char -> EndorserBlockHash
eb :: Char -> EndorserBlockHash
eb Char
c = ShortByteString -> EndorserBlockHash
forall h a.
(HashAlgorithm h, HasCallStack) =>
ShortByteString -> Hash h a
UnsafeHash (ShortByteString -> EndorserBlockHash)
-> ShortByteString -> EndorserBlockHash
forall a b. (a -> b) -> a -> b
$ [Word8] -> ShortByteString
SBS.pack ([Word8] -> ShortByteString) -> [Word8] -> ShortByteString
forall a b. (a -> b) -> a -> b
$ Int -> Word8 -> [Word8]
forall a. Int -> a -> [a]
replicate Int
32 (Int -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Char -> Int
forall a. Enum a => a -> Int
fromEnum Char
c))

-- | The bounds these scenarios forecast: large enough that nothing here trips
-- them.
anyBounds :: SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes SizeLimit)
anyBounds :: SlotNo -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
anyBounds SlotNo
_slot = LeiosEbByteSizes 'SizeLimit
-> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
forall a b. b -> Either a b
Right LeiosEbByteSizes 'SizeLimit
forall a. Bounded a => a
maxBound