-
Notifications
You must be signed in to change notification settings - Fork 86
/
PeerSelection.hs
3636 lines (3215 loc) · 152 KB
/
PeerSelection.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralisedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeApplications #-}
{-# OPTIONS_GHC -Wno-orphans #-}
-- TODO: remove it once #3601 is fixed
{-# OPTIONS_GHC -Wno-unused-top-binds #-}
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
#if __GLASGOW_HASKELL__ >= 908
{-# OPTIONS_GHC -Wno-x-partial #-}
#endif
module Test.Ouroboros.Network.PeerSelection
( tests
, unfHydra
, takeBigLedgerPeers
, dropBigLedgerPeers
) where
import Data.Bifoldable (bitraverse_)
import Data.ByteString.Char8 qualified as BS
import Data.Foldable (traverse_)
import Data.Function (on)
import Data.IP qualified as IP
import Data.List (foldl', groupBy, intercalate)
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe (fromMaybe, isNothing, listToMaybe)
import Data.Set (Set)
import Data.Set qualified as Set
import Data.Void (Void)
import Data.List.Trace qualified as Trace
import Data.OrdPSQ qualified as PSQ
import System.Random (mkStdGen)
import Control.Exception (AssertionFailed (..), catch, evaluate)
import Control.Monad.Class.MonadSTM (STM, retry)
import Control.Monad.Class.MonadTimer.SI
import Control.Tracer (Tracer (..))
import Network.DNS qualified as DNS (defaultResolvConf)
import Network.Socket (SockAddr)
import Ouroboros.Network.PeerSelection.Governor hiding (PeerSelectionState (..),
peerSharing)
import Ouroboros.Network.PeerSelection.Governor qualified as Governor
import Ouroboros.Network.PeerSelection.State.EstablishedPeers qualified as EstablishedPeers
import Ouroboros.Network.PeerSelection.State.KnownPeers qualified as KnownPeers
import Ouroboros.Network.PeerSelection.State.LocalRootPeers qualified as LocalRootPeers
import Ouroboros.Network.ConnectionManager.Test.Timeouts (AllProperty (..))
import Ouroboros.Network.Testing.Data.Script
import Ouroboros.Network.Testing.Data.Signal (E (E), Events, Signal, TS (TS),
signalProperty)
import Ouroboros.Network.Testing.Data.Signal qualified as Signal
import Ouroboros.Network.Testing.Utils (nightlyTest)
import Test.Ouroboros.Network.PeerSelection.Instances
import Test.Ouroboros.Network.PeerSelection.MockEnvironment hiding (tests)
import Test.Ouroboros.Network.PeerSelection.PeerGraph
import Control.Concurrent.Class.MonadSTM.Strict (newTVarIO)
import Control.Monad.Class.MonadTime.SI
import Control.Monad.IOSim
import Ouroboros.Network.ExitPolicy (RepromoteDelay (..))
import Ouroboros.Network.PeerSelection.Bootstrap (UseBootstrapPeers (..),
requiresBootstrapPeers)
import Ouroboros.Network.PeerSelection.LedgerPeers
import Ouroboros.Network.PeerSelection.PeerAdvertise
import Ouroboros.Network.PeerSelection.PeerSharing (PeerSharing (..))
import Ouroboros.Network.PeerSelection.PeerTrustable (PeerTrustable (..))
import Ouroboros.Network.PeerSelection.PublicRootPeers (PublicRootPeers)
import Ouroboros.Network.PeerSelection.PublicRootPeers qualified as PublicRootPeers
import Ouroboros.Network.PeerSelection.RootPeersDNS.DNSActions
import Ouroboros.Network.PeerSelection.RootPeersDNS.DNSSemaphore
import Ouroboros.Network.PeerSelection.RootPeersDNS.PublicRootPeers
import Ouroboros.Network.PeerSelection.State.LocalRootPeers
import Ouroboros.Network.Protocol.PeerSharing.Type (PeerSharingResult (..))
import Test.QuickCheck
import Test.Tasty
import Test.Tasty.QuickCheck
import Text.Pretty.Simple
-- Exactly as named.
unfHydra :: Int
unfHydra = 1
tests :: TestTree
tests =
testGroup "Ouroboros.Network.PeerSelection"
[ testGroup "basic"
[ testProperty "has output" prop_governor_hasoutput
, testProperty "no failure" prop_governor_nofail
, testProperty "no livelock" prop_governor_nolivelock
]
-- The no livelock property is needed to ensure other tests terminate
, after AllSucceed "Ouroboros.Network.PeerSelection.basic" $
testGroup "safety"
[ testProperty "no excess busyness" prop_governor_nobusyness
, testProperty "event coverage" prop_governor_trace_coverage
, testProperty "connection status" prop_governor_connstatus
, testProperty "event number coverage" prop_governor_events_coverage
]
-- The no livelock property is needed to ensure other tests terminate
, after AllSucceed "Ouroboros.Network.PeerSelection.basic" $
testGroup "progress"
[ testGroup "ledger peers"
[ testProperty "progresses towards known target (from below)"
prop_governor_target_known_below
, testProperty "progresses towards known target (from above)"
prop_governor_target_known_above
, testProperty "progresses towards established target (from below)"
prop_governor_target_established_below
, testProperty "progresses towards established target (from above)"
prop_governor_target_established_above
, testProperty "progresses towards active target (from below)"
prop_governor_target_active_below
, testProperty "progresses towards active target (from above)"
prop_governor_target_active_above
]
, testGroup "public root peers"
[ testProperty "progresses towards target (from below)"
prop_governor_target_root_below
, testProperty "progresses towards established peers"
prop_governor_target_established_public
, testProperty "progresses towards active peers"
prop_governor_target_active_public
]
, testGroup "local root peers"
[ testProperty "progresses towards established target"
prop_governor_target_established_local
, testProperty "progresses towards active target (from below)"
prop_governor_target_active_local_below
, testProperty "progresses towards active target (from above)"
prop_governor_target_active_local_above
]
, testGroup "big ledger peers"
[ testProperty "progresses towards known target (from below)"
prop_governor_target_known_big_ledger_peers_below
, testProperty "progresses towards known target (from above)"
prop_governor_target_known_big_ledger_peers_above
, testProperty "progresses towards established target"
prop_governor_target_established_big_ledger_peers
, testProperty "progresses towards established target (from below)"
prop_governor_target_established_big_ledger_peers_below
, testProperty "progresses towards established target (from above)"
prop_governor_target_established_big_ledger_peers_above
, testProperty "progresses towards active target (from below)"
prop_governor_target_active_big_ledger_peers_below
, testProperty "progresses towards active target (from above)"
prop_governor_target_active_big_ledger_peers_above
]
, testGroup "bootstrap peers"
[ testProperty "progress towards only bootstrap peers after changing to fallback state"
prop_governor_only_bootstrap_peers_in_fallback_state
, testProperty "node does not learn about non trustable peers when in fallback state"
prop_governor_no_non_trustable_peers_before_caught_up_state
, testProperty "node only use bootstrap peers if in sensitive state"
prop_governor_stops_using_bootstrap_peers
, testProperty "node never uses non-trustable peers after clean state"
prop_governor_only_bootstrap_peers_after_clean_state
, testProperty "node uses ledger peers in non-sensitive mode"
prop_governor_uses_ledger_peers
]
]
, testGroup "issues"
[ testProperty "3233" prop_issue_3233
, testProperty "3494" prop_issue_3494
, testProperty "3515" prop_issue_3515
, testProperty "3550" prop_issue_3550
]
, testProperty "governor repromote delay with fuzz" prop_governor_repromote_delay
, testProperty "governor peer share reachable in 1hr" prop_governor_peershare_1hr
, testProperty "governor connection status" prop_governor_connstatus
, testProperty "governor no livelock" prop_governor_nolivelock
, testGroup "races"
[ nightlyTest $ testProperty "governor no livelock" $ prop_explore_governor_nolivelock
, nightlyTest $ testProperty "governor connection status" $ prop_explore_governor_connstatus
]
]
--TODO: We should add separate properties to check that we do not overshoot
-- our targets: known peers from below can overshoot, but all the others
-- should be precise and not overshoot. The public root target from below
-- is a one-sided target and we can and will overshoot, but we should not
-- overshoot by too much.
--
-- QuickCheck properties
--
-- We start with basic properties in the style of "never does bad things"
-- and progress to properties that check that it "eventually does good things".
--
-- In the "never does bad things" category we have:
--
-- * A basic state space exploration property that checks we don't encounter
-- internal errors. This includes some limited checking that we get adequate
-- coverage of the different actions, by looking for coverage of all the
-- trace events. The coverage checks here are useful to give us confidence
-- about coverage for some of the other properties.
--
-- * A no-livelock property. This checks that the governor does not get stuck
-- doing too many steps at a single moment in (virtual) time. It's quite easy
-- to write bugs that don't cause the governor to fail, but cause it to go
-- into a busy cycle. See also the "no excessive busyness" property for a
-- more advanced version.
--
-- * A "no excessive busyness" property. This checks that the governor does not
-- remain too busy for too long. It's quite easy to write bugs that don't
-- cause the governor to fail, but cause it to go into fairly-busy cycles.
--
-- * A state consistency property that the governor's view of part of the state
-- and the "true" state of the mock environment are maintained in an
-- appropriate correspondence.
--
-- In the "eventually does good things" category we have:
--
-- * A basic property to check the governor does produce non-trivial traces.
--
-- * A cold peer peer sharing "reachable" property: that the governor either hits
-- its target for the number of cold peers, or finds all the reachable peers.
--
-- * A known peer target progress property: that the governor makes progress
-- within a bounded time towards its known peers target, from below and above.
--
-- * An established peer target property: the same as above but for established
-- peers.
--
-- * An active peer target property: the same as above but for active peers.
--
-- Properties that we would like to have:
--
-- * A public root peers target property: that the governor hits its target for
-- for the number of public root peers (or as near as possible), and does
-- not "grossly" overshoot. Since the public roots is a one sided target, but
-- we don't want to overshoot excessively.
--
-- * A local root peers target property: that the governor hits its target for
-- getting all its local root peers into the established state, and a target
-- number of them into the active state (or as near as possible).
--
-- Other properties we might like to think about
--
-- * time to find new nodes after a graph change is ok
-- * targets or root peer set dynamic
-- | As the most basic property we run the governor and check that it produces
-- any trace output at all. It should elicit some activity, unless the test
-- environment is actually empty.
--
prop_governor_hasoutput :: GovernorMockEnvironment -> Property
prop_governor_hasoutput env =
let trace = runGovernorInMockEnvironment env
evs = selectPeerSelectionTraceEvents trace
in counterexample (unlines ["\nSIM TRACE", ppTrace trace])
$ counterexample (unlines . ("EVENTS" :) . map show $ evs)
$ hasOutput env (selectGovernorEvents evs)
hasOutput :: GovernorMockEnvironment
-> [(Time, TracePeerSelection PeerAddr)]
-> Bool
hasOutput _ (_:_) = True
hasOutput env [] = isEmptyEnv env
isEmptyEnv :: GovernorMockEnvironment -> Bool
isEmptyEnv GovernorMockEnvironment {
localRootPeers,
publicRootPeers,
targets
} =
(LocalRootPeers.null localRootPeers
|| all (\(t,_) -> targetNumberOfKnownPeers t == 0) targets)
&& (PublicRootPeers.null publicRootPeers
|| all (\(t,_) -> targetNumberOfRootPeers t == 0) targets)
-- | As a basic property we run the governor to explore its state space a bit
-- and check it does not throw any exceptions (assertions such as invariant
-- violations).
--
-- We do /not/ assume freedom from livelock for this property, so we run the
-- governor for a maximum number of trace events rather than for a fixed
-- simulated time.
--
prop_governor_nofail :: GovernorMockEnvironment -> Property
prop_governor_nofail env =
let ioSimTrace = runGovernorInMockEnvironment env
trace = take 5000
. selectPeerSelectionTraceEvents
$ ioSimTrace
-- run in `IO` so we can catch the pure 'AssertionFailed' exception
in ioProperty $ do
r <-
evaluate ( foldl' (flip seq) True
$ [ assertPeerSelectionState st ()
| (_, GovernorDebug (TraceGovernorState _ _ st)) <- trace ]
)
`catch` \(AssertionFailed _) -> return False
case r of
True -> return $ property True
False -> do
bitraverse_ (putStrLn . show)
(putStrLn . ppSimEvent 20 20 20)
ioSimTrace
-- the ioSimTrace is infinite, but it will terminate with `AssertionFailed`
error "impossible!"
-- | It is relatively easy to write bugs where the governor is stuck in a tight
-- cycle of continuous activity. Due to the way the I\/O simulator manages
-- virtual time, these bugs exhibits themselves by infinite trace activity
-- without time advancing.
--
-- It is important to catch these bugs early in the set of tests, since it is
-- hard to write many of the other more interesting properties if there are
-- these kinds of livelock bugs. Or to put it another way, the other properties
-- can be expressed more simply if they can assume within event traces that the
-- time always advances after some finite number of events.
--
prop_governor_nolivelock :: GovernorMockEnvironment -> Property
prop_governor_nolivelock env =
check_governor_nolivelock 5000 $ runGovernorInMockEnvironment env
prop_explore_governor_nolivelock :: GovernorMockEnvironment -> Property
prop_explore_governor_nolivelock =
-- Simulation steps take longer and longer as simulated time
-- advances; running time for this property is quadratic in the
-- number of events explored. We limit the test to 500 governor
-- events to avoid unreasonably slow tests. This may be because
-- the governor becomes slower over time with priority-based
-- scheduling, or because IOSimPOR's data structures grow.
-- This test currently fails, because of a broken assertion in
-- Ouroboros.Network.PeerSelection.Governor.ActivePeers, which
-- checks that a newly promoted warm peer is a member of the set
-- of established peers. This may not be true if the promotion is
-- delayed by a race condition.
prop'_explore_governor_nolivelock id 500
prop'_explore_governor_nolivelock :: ExplorationSpec -> Int -> GovernorMockEnvironment -> Property
prop'_explore_governor_nolivelock spec len env =
exploreGovernorInMockEnvironment spec env $ \_ trace ->
-- counterexample (showTrace trace) $
-- whenfail (pPrint env) $
check_governor_nolivelock len trace
check_governor_nolivelock :: Int -> SimTrace a -> Property
check_governor_nolivelock n trace0 =
let trace = take n .
selectGovernorEvents .
selectPeerSelectionTraceEvents $
trace0
in case tooManyEventsBeforeTimeAdvances 1000 trace of
Nothing -> property True
Just (t, es) ->
counterexample
("over 1000 events at time: " ++ show t ++ "\n" ++
"first 50 events: " ++ (unlines . map show . take 50 $ es)) $
property False
{-
showTrace = break . show
where break s | "(Trace " `isPrefixOf` s = "\n" ++ breaks
| otherwise = breaks
where breaks | null s = []
| otherwise = head s : break (tail s)
-}
-- | Scan the trace and return any occurrence where we have at least threshold
-- events before virtual time moves on. Return the tail of the trace from that
-- point on.
--
tooManyEventsBeforeTimeAdvances :: Int -> [(Time, e)] -> Maybe (Time, [e])
tooManyEventsBeforeTimeAdvances _ [] = Nothing
tooManyEventsBeforeTimeAdvances threshold trace0 =
go [ (t, diffTime t' t, e)
| ((t, e), (t', _)) <- zip trace0 (tail trace0) ]
where
go [] = Nothing
go trace@((t,_,_):_) = case countdown threshold trace of
Just es' -> go es'
Nothing -> Just (t, trace')
where
trace' = take threshold [ e | (_,_,e) <- trace ]
countdown 0 _ = Nothing
countdown _ [] = Just []
countdown n ((_t,dt,_e):es)
| dt == 0 = countdown (n-1) es
| otherwise = Just es
-- | It is easy to get bugs where the governor is stuck in a cycle, working but
-- not making progress. This kind of bug would result in the governor thread
-- being excessively busy, so it might not be easily noticed.
--
-- This is more subtle and general than a simple livelock test that just checks
-- we don't get completely stuck. This property is about the possibility that
-- the governor is excessively busy over some period of time. This includes
-- "slow" livelocks where time advances during some of the steps in the cycle.
-- More interestingly this is also about a failure to converge and return to
-- being idle sufficiently quickly.
--
-- For example the governor could gets stuck in a cycle promoting and demoting
-- a peer once a second. In such a failure mode it will have a continuous level
-- of activity and will not return to being idle (perhaps ever or perhaps for
-- an extended period until some other environment perturbation gets us out of
-- the cycle).
--
-- The approach we take is based on the observation that the governor can
-- (quite reasonably) start with a big burst of activity (e.g. as it peer shares
-- to discover a big graph) but that in the long term it settles down and only
-- has small bursts of activity in reaction to perturbations in the environment
-- such as failures or changes in targets.
--
-- The approach we take is to look at spans of busy activity followed by
-- periods of idleness. If the spans of busy activity are too long then we
-- fail. So this counts the time of busyness not the number of events. We
-- account for activity in the environment that the governor needs to respond
-- to by counting \"perturbation credits"\: more credits means we allow longer
-- spans of busyness.
--
-- More specifically: we look at runs of events where the time between events
-- is less than a threshold. This implies there follows a threshold level of
-- idleness. Starting or within that run of events there can be environment
-- events. These are the perturbations from the environment that we expect to
-- trigger a series of responses from the governor. So we expect longer periods
-- of business for bigger perturbations. We sum all the perturbations credits
-- included in a run of events. We use a formula that relates the credits to
-- the permitted time span of the run. If the run is within the permitted time
-- span then it is ok, otherwise it is a failure (and the run is the
-- counterexample).
--
-- TODO: This test uses static root peers, but we should move to dynamic root
-- peers.
--
prop_governor_nobusyness :: GovernorMockEnvironment -> Property
prop_governor_nobusyness env =
let trace = selectPeerSelectionTraceEvents $
runGovernorInMockEnvironment env
in case tooBusyForTooLong (takeFirstNHours 10 trace) of
Nothing -> property True
Just (busyStartTime, busyEndTime, credits, trace') ->
counterexample
("busy span too long\n" ++
"start time: " ++ show busyStartTime ++ "\n" ++
"end time: " ++ show busyEndTime ++ "\n" ++
"span credits: " ++ show credits ++ "\n" ++
"first 50 events:\n" ++
(unlines . map show . take 50 $ trace')) $
property False
--
tooBusyForTooLong :: [(Time, TestTraceEvent)]
-> Maybe (Time, Time, DiffTime,
[(Time, TestTraceEvent)])
tooBusyForTooLong trace0 =
-- Pass in each timed event, with the diff-time to the next event
idle [ (t, diffTime t' t, e)
| ((t, e), (t', _)) <- zip trace0 (tail trace0) ]
where
-- How long between events before we say it's the end of a busy span
sameSpanThreshold :: DiffTime
sameSpanThreshold = 45
-- Starting credits for a busy span, even if there are no triggering
-- environment events. The value chosen here takes account of the normal
-- exponential backoff is 2+4+8+16+32 = 62, before a gap of 64 that's
-- bigger than the sameSpanThreshold of 45.
initialEventCredits :: DiffTime
initialEventCredits = 65
-- We process the event trace linearly, flipping between two states: idle
-- and busy. In the idle state, the next (non-debug) event flips us into
-- the busy state, starting with some minimal initial credits.
idle :: [(Time, DiffTime, TestTraceEvent)]
-> Maybe (Time, Time, DiffTime, [(Time, TestTraceEvent)])
idle [] = Nothing
idle ((_, _, GovernorDebug{}):trace') = idle trace'
idle trace@((busyStartTime,_,_):_) =
case busy busyStartTime initialEventCredits trace of
Right trace' -> idle trace'
Left (busyEndTime, credits) ->
Just (busyStartTime, busyEndTime, credits, trace')
where
trace' = [ (t, e)
| (t,_dt, e) <-
takeWhile (\(t,_,_) -> t <= busyEndTime) trace
, case e of
GovernorDebug{} -> False
_ -> True
]
busy :: Time -> DiffTime -> [(Time, DiffTime, TestTraceEvent)]
-> Either (Time, DiffTime) [(Time, DiffTime, TestTraceEvent)]
-- For normal governor events we check if the length of the busy time span
-- is now too big (adjusted for any perturbation credits). If so we've
-- found a violation.
busy !busyStartTime !credits ((busyEndTime, _dt, GovernorEvent{}) : _trace')
| busySpanLength > credits = Left (busyEndTime, credits)
where
busySpanLength = diffTime busyEndTime busyStartTime
-- We also look at how long it is to the next event to see if this is the
-- last event in the busy span, and if so we return to idle.
busy !_busyStartTime !_credits ((_t, dt, _event) : trace')
| dt > sameSpanThreshold = Right trace'
-- For environment events we calculate the perturbation credits this
-- contributes and add it to our running total.
busy !busyStartTime !credits ((_, _, MockEnvEvent e) : trace') =
busy busyStartTime (credits + fromIntegral (envEventCredits e)) trace'
-- Otherwise we move on to the next event, updating the length of this busy
-- time span.
busy !busyStartTime !credits (_ : trace') =
busy busyStartTime credits trace'
-- running out of events before we find a violation is ok
busy !_ !_ [] = Right []
envEventCredits :: TraceMockEnv -> Int
envEventCredits (TraceEnvAddPeers peerGraph) = 80 * 5 + length adjacency * 5
where
PeerGraph adjacency = peerGraph
envEventCredits (TraceEnvSetLocalRoots peers) = LocalRootPeers.size peers
envEventCredits (TraceEnvSetPublicRoots peers) = PublicRootPeers.size peers
envEventCredits TraceEnvRequestPublicRootPeers = 0
envEventCredits TraceEnvRequestBigLedgerPeers = 0
envEventCredits TraceEnvPublicRootTTL = 60
envEventCredits TraceEnvBigLedgerPeersTTL = 60
envEventCredits (TraceEnvSetTargets PeerSelectionTargets {
targetNumberOfRootPeers = _,
targetNumberOfKnownPeers,
targetNumberOfEstablishedPeers,
targetNumberOfActivePeers
}) = 80
+ 10 * (targetNumberOfKnownPeers
+ targetNumberOfEstablishedPeers
+ targetNumberOfActivePeers)
envEventCredits (TraceEnvPeersDemote Noop _) = 10
envEventCredits (TraceEnvPeersDemote ToWarm _) = 30
envEventCredits (TraceEnvPeersDemote ToCooling _) = 30
envEventCredits (TraceEnvPeersDemote ToCold _) = 30
envEventCredits TraceEnvPeersStatus{} = 0
-- These events can return emty results which will actually result in the governor
-- to issue more since it wasn't able to make progress towards the target.
-- However, the governor won't be making infinite requests, and ending up on a
-- livelock. Given this, in the case it doesn't manage to make
-- progress we give it a little bit of credits in order to account for the
-- next request.
--
envEventCredits TraceEnvPeerShareResult{} = 10
envEventCredits TraceEnvRootsResult{} = 10
envEventCredits TraceEnvBigLedgerPeersResult{} = 10
-- These events are visible in the environment but are the result of actions
-- initiated by the governor, hence they get no credit.
envEventCredits TraceEnvPeerShareRequest{} = 0
envEventCredits TraceEnvPeerShareTTL {} = 0
envEventCredits TraceEnvEstablishConn {} = 0
envEventCredits TraceEnvActivatePeer {} = 0
envEventCredits TraceEnvDeactivatePeer {} = 0
envEventCredits TraceEnvCloseConn {} = 0
envEventCredits TraceEnvSetLedgerStateJudgement {} = 30
envEventCredits TraceEnvSetUseBootstrapPeers {} = 30
-- | A coverage property that checks how many events are analysed when taking
-- up to 10h of execution time.
--
prop_governor_events_coverage :: GovernorMockEnvironment -> Property
prop_governor_events_coverage env =
let trace = Signal.eventsToList
. Signal.eventsFromListUpToTime (Time (10 * 60 * 60))
. selectPeerSelectionTraceEvents
. runGovernorInMockEnvironment
$ env
printLength x
| x < 10 = "# events < 10"
| x >= 10 && x < 100 = "# events >= 10 && < 100"
| x >= 100 && x < 1000 = "# events >= 100 && < 1000"
| x >= 1000 && x < 10000 = "# events >= 1000 && < 10000"
| x >= 10000 && x < 100000 = "# events >= 10000 && < 100000"
| x >= 100000 && x < 1000000 = "# events >= 100000 && < 1000000"
| otherwise = "# events >= 1000000"
in tabulate "# events" [printLength (length trace)]
True
-- | A coverage property, much like 'prop_governor_nofail' but we look to see
-- that we get adequate coverage of the state space. We look for all the trace
-- events that the governor can produce, and tabules which ones we see.
--
prop_governor_trace_coverage :: GovernorMockEnvironment -> Property
prop_governor_trace_coverage env =
let trace = take 5000 .
selectPeerSelectionTraceEvents $
runGovernorInMockEnvironment env
traceNumsSeen = collectTraces trace
traceNamesSeen = allTraceNames `Map.restrictKeys` traceNumsSeen
in coverTable "trace events" [ (n, 1) | n <- Map.elems allTraceNames ] $
tabulate "trace events" (Map.elems traceNamesSeen)
True
--TODO: use cover to check we do indeed get them all. There are a few
-- cases we do not cover yet. These should be fixed first.
collectTraces :: [(Time, TestTraceEvent)] -> Set Int
collectTraces trace =
Set.fromList [ traceNum e | (_, GovernorEvent e) <- trace ]
traceNum :: TracePeerSelection peeraddr -> Int
traceNum TraceLocalRootPeersChanged{} = 00
traceNum TraceTargetsChanged{} = 01
traceNum TracePublicRootsRequest{} = 02
traceNum TracePublicRootsResults{} = 03
traceNum TracePublicRootsFailure{} = 04
traceNum TracePeerShareRequests{} = 05
traceNum TracePeerShareResults{} = 06
traceNum TracePeerShareResultsFiltered{} = 07
traceNum TraceForgetColdPeers{} = 08
traceNum TracePromoteColdPeers{} = 09
traceNum TracePromoteColdLocalPeers{} = 10
traceNum TracePromoteColdFailed{} = 11
traceNum TracePromoteColdDone{} = 12
traceNum TracePromoteWarmPeers{} = 13
traceNum TracePromoteWarmLocalPeers{} = 14
traceNum TracePromoteWarmFailed{} = 15
traceNum TracePromoteWarmDone{} = 16
traceNum TraceDemoteWarmPeers{} = 17
traceNum TraceDemoteWarmFailed{} = 18
traceNum TraceDemoteWarmDone{} = 19
traceNum TraceDemoteHotPeers{} = 20
traceNum TraceDemoteLocalHotPeers{} = 21
traceNum TraceDemoteHotFailed{} = 22
traceNum TraceDemoteHotDone{} = 23
traceNum TraceDemoteAsynchronous{} = 24
traceNum TraceGovernorWakeup{} = 25
traceNum TraceChurnWait{} = 26
traceNum TraceChurnMode{} = 27
traceNum TracePromoteWarmAborted{} = 28
traceNum TraceDemoteLocalAsynchronous{} = 29
traceNum TraceBigLedgerPeersRequest{} = 30
traceNum TraceBigLedgerPeersResults{} = 31
traceNum TraceBigLedgerPeersFailure{} = 32
traceNum TraceForgetBigLedgerPeers{} = 33
traceNum TracePromoteColdBigLedgerPeers{} = 34
traceNum TracePromoteColdBigLedgerPeerFailed{} = 35
traceNum TracePromoteColdBigLedgerPeerDone{} = 36
traceNum TracePromoteWarmBigLedgerPeers{} = 37
traceNum TracePromoteWarmBigLedgerPeerFailed{} = 38
traceNum TracePromoteWarmBigLedgerPeerDone{} = 39
traceNum TracePromoteWarmBigLedgerPeerAborted{} = 40
traceNum TraceDemoteWarmBigLedgerPeers{} = 41
traceNum TraceDemoteWarmBigLedgerPeerFailed{} = 42
traceNum TraceDemoteWarmBigLedgerPeerDone{} = 43
traceNum TraceDemoteHotBigLedgerPeers{} = 44
traceNum TraceDemoteHotBigLedgerPeerFailed{} = 45
traceNum TraceDemoteHotBigLedgerPeerDone{} = 46
traceNum TraceKnownInboundConnection{} = 47
traceNum TraceDemoteBigLedgerPeersAsynchronous{} = 48
traceNum TraceLedgerStateJudgementChanged{} = 49
traceNum TraceOnlyBootstrapPeers{} = 50
traceNum TraceBootstrapPeersFlagChangedWhilstInSensitiveState = 51
traceNum TraceUseBootstrapPeersChanged {} = 52
traceNum TraceOutboundGovernorCriticalFailure {} = 53
traceNum TraceDebugState {} = 54
traceNum TraceChurnAction {} = 55
traceNum TraceChurnTimeout {} = 56
allTraceNames :: Map Int String
allTraceNames =
Map.fromList
[ (00, "TraceLocalRootPeersChanged")
, (01, "TraceTargetsChanged")
, (02, "TracePublicRootsRequest")
, (03, "TracePublicRootsResults")
, (04, "TracePublicRootsFailure")
, (05, "TracePeerShareRequests")
, (06, "TracePeerShareResults")
, (07, "TracePeerShareResultsFiltered")
, (08, "TraceForgetColdPeers")
, (09, "TracePromoteColdPeers")
, (10, "TracePromoteColdLocalPeers")
, (11, "TracePromoteColdFailed")
, (12, "TracePromoteColdDone")
, (13, "TracePromoteWarmPeers")
, (14, "TracePromoteWarmLocalPeers")
, (15, "TracePromoteWarmFailed")
, (16, "TracePromoteWarmDone")
, (17, "TraceDemoteWarmPeers")
, (18, "TraceDemoteWarmFailed")
, (19, "TraceDemoteWarmDone")
, (20, "TraceDemoteHotPeers")
, (21, "TraceDemoteLocalHotPeers")
, (22, "TraceDemoteHotFailed")
, (23, "TraceDemoteHotDone")
, (24, "TraceDemoteAsynchronous")
, (25, "TraceGovernorWakeup")
, (26, "TraceChurnWait")
, (27, "TraceChurnMode")
, (28, "TracePromoteWarmAborted")
, (29, "TraceDemoteAsynchronous")
, (30, "TraceBigLedgerPeersRequest")
, (31, "TraceBigLedgerPeersResults")
, (32, "TraceBigLedgerPeersFailure")
, (33, "TraceForgetBigLedgerPeers")
, (34, "TracePromoteColdBigLedgerPeers")
, (35, "TracePromoteColdBigLedgerPeerFailed")
, (36, "TracePromoteColdBigLedgerPeerDone")
, (37, "TracePromoteWarmBigLedgerPeers")
, (38, "TracePromoteWarmBigLedgerPeerFailed")
, (39, "TracePromoteWarmBigLedgerPeerDone")
, (40, "TracePromoteWarmBigLedgerPeerAborted")
, (41, "TraceDemoteWarmBigLedgerPeers")
, (42, "TraceDemoteWarmBigLedgerPeerFailed")
, (43, "TraceDemoteWarmBigLedgerPeerDone")
, (44, "TraceDemoteHotBigLedgerPeers")
, (45, "TraceDemoteHotBigLedgerPeerFailed")
, (46, "TraceDemoteHotBigLedgerPeerDone")
, (47, "TraceKnownInboundConnection")
, (48, "TraceDemoteBigLedgerPeersAsynchronous")
, (49, "TraceLedgerStateJudgementChanged")
, (50, "TraceOnlyBootstrapPeers")
, (51, "TraceBootstrapPeersFlagChangedWhilstInSensitiveState")
, (52, "TraceUseBootstrapPeersChanged")
, (53, "TraceOutboundGovernorCriticalFailure")
, (54, "TraceDebugState")
, (55, "TraceChurnAction")
, (56, "TraceChurnTimeout")
]
-- | Run the governor for up to 1 hour (simulated obviously) and look at the
-- set of known peers it has selected. This uses static targets and root peers.
--
-- As a basic correctness property, the peers the governor selects must be a
-- subset of those that are in principle reachable in the mock network
-- environment.
--
-- More interestingly, we expect the governor to find enough peers. However,
-- one can not test that it will find all reachable addresses, since we only
-- peer share with established peers and the mock environment might never promote
-- the peer that would allow us to reach every other peer.
--
prop_governor_peershare_1hr :: GovernorMockEnvironment -> Property
prop_governor_peershare_1hr env@GovernorMockEnvironment {
peerGraph,
localRootPeers,
publicRootPeers,
targets
} =
let ioSimTrace = runGovernorInMockEnvironment env {
targets = singletonScript (targets', NoDelay)
}
trace = selectPeerSelectionTraceEvents ioSimTrace
Just found = knownPeersAfter1Hour trace
reachable = peerShareReachablePeers peerGraph
(LocalRootPeers.keysSet localRootPeers <> PublicRootPeers.toSet publicRootPeers)
in counterexample ( intercalate "\n"
. map (ppSimEvent 20 20 20)
. takeWhile (\e -> seTime e <= Time (60*60))
. Trace.toList
$ ioSimTrace) $
subsetProperty found reachable
where
-- This test is only about testing peer sharing,
-- so do not try to establish connections:
targets' :: PeerSelectionTargets
targets' = fst (scriptHead targets)
knownPeersAfter1Hour :: [(Time, TestTraceEvent)] -> Maybe (Set PeerAddr)
knownPeersAfter1Hour trace =
listToMaybe
[ KnownPeers.toSet (Governor.knownPeers st)
| (_, GovernorDebug (TraceGovernorState _ _ st))
<- reverse (takeFirstNHours 1 trace)
]
-- The ones we find should be a subset of the ones possible to find
subsetProperty found reachable =
counterexample ("reachable: " ++ show reachable ++ "\n" ++
"found: " ++ show found) $
property (found `Set.isSubsetOf` reachable)
-- | Check the governor's view of connection status does not lag behind reality
-- by too much.
--
prop_governor_connstatus :: GovernorMockEnvironment -> Property
prop_governor_connstatus env =
check_governor_connstatus Nothing (runGovernorInMockEnvironment env)
-- The explore version of this property fails, I think because the
-- assumption made in the check that status events appear in the trace
-- in the correct order is broken by a race.
prop_explore_governor_connstatus :: GovernorMockEnvironment -> Property
prop_explore_governor_connstatus = prop'_explore_governor_connstatus id
prop'_explore_governor_connstatus :: ExplorationSpec -> GovernorMockEnvironment -> Property
prop'_explore_governor_connstatus opts env =
whenFail (pPrint env) $
exploreGovernorInMockEnvironment opts env check_governor_connstatus
check_governor_connstatus :: Maybe (SimTrace a) -> SimTrace a -> Property
check_governor_connstatus _ trace0 =
let trace = takeFirstNHours 1
. selectPeerSelectionTraceEvents $ trace0
--TODO: check any actually get a true status output and try some deliberate bugs
in
whenFail (traverse_ print trace) $
conjoin $ map ok (groupBy ((==) `on` fst) trace)
where
-- We look at events when the environment's view of the state of all the
-- peer connections changed, and check that before simulated time advances
-- the governor's view of the same state was brought in sync.
--
-- We do that by finding the env events and then looking for the last
-- governor state event before time moves on.
ok :: [(Time, TestTraceEvent)] -> Property
ok trace =
counterexample ("last few events:\n" ++ (unlines . map show) trace) $
case (lastEnvStatus, lastGovStatus) of
(Nothing, _) -> property True
(Just envStatus, Just govStatus) -> envStatus === govStatus
(Just envStatus, Nothing) -> envStatus === Map.empty
where
lastEnvStatus =
listToMaybe
[ Map.filter (not . isPeerCooling) status
| (_, MockEnvEvent (TraceEnvPeersStatus status)) <- reverse trace ]
isPeerCooling PeerCooling = True
isPeerCooling _ = False
lastGovStatus =
listToMaybe
[ Governor.establishedPeersStatus st
| (_, GovernorDebug (TraceGovernorState _ _ st)) <- reverse trace ]
--
-- Progress properties
--
-- | A variant of 'prop_governor_target_established_below' but for the target
-- number of root peers.
--
-- Check that the governor can hit (but not overshoot) its target for the
-- number of root peers. This has to be bounded by what is possible: we cannot
-- always find enough peers, and when we can, some of them fail.
--
prop_governor_target_root_below :: GovernorMockEnvironment -> Property
prop_governor_target_root_below env =
let events = Signal.eventsFromListUpToTime (Time (10 * 60 * 60))
. selectPeerSelectionTraceEvents
. runGovernorInMockEnvironment
$ env
govTargetsSig :: Signal Int
govTargetsSig =
selectGovState (targetNumberOfRootPeers . Governor.targets) events
govLocalRootPeersSig :: Signal (Set PeerAddr)
govLocalRootPeersSig =
selectGovState (LocalRootPeers.keysSet . Governor.localRootPeers) events
govPublicRootPeersSig :: Signal (Set PeerAddr)
govPublicRootPeersSig =
selectGovState (PublicRootPeers.toSet . Governor.publicRootPeers) events
govRootPeersSig :: Signal (Set PeerAddr)
govRootPeersSig = Set.union <$> govLocalRootPeersSig <*> govPublicRootPeersSig
-- There are no opportunities if we're at or above target
--
requestOpportunity target public roots
| Set.size roots >= target
= Set.empty
| otherwise
= public Set.\\ roots
requestOpportunities :: Signal (Set PeerAddr)
requestOpportunities =
requestOpportunity
<$> govTargetsSig
<*> govPublicRootPeersSig
<*> govRootPeersSig
requestOpportunitiesIgnoredTooLong :: Signal (Set PeerAddr)
requestOpportunitiesIgnoredTooLong =
Signal.keyedTimeout
10 -- seconds
id
requestOpportunities
in counterexample
("\nSignal key: (target, local peers, public peers, root peers, " ++
"opportunities, ignored too long)") $
signalProperty 20 show
(\(_,_,_,_,_,toolong) -> Set.null toolong)
((,,,,,) <$> govTargetsSig
<*> govLocalRootPeersSig
<*> govPublicRootPeersSig
<*> govRootPeersSig
<*> requestOpportunities
<*> requestOpportunitiesIgnoredTooLong)
-- | A variant of 'prop_governor_target_established_below' but for the target
-- that any public root peers should become established.
--
-- We do not need separate above and below variants of this property since it
-- is not possible to exceed the target.
--
prop_governor_target_established_public :: MaxTime -> GovernorMockEnvironment -> Property
prop_governor_target_established_public (MaxTime maxTime) env =
let events = Signal.eventsFromListUpToTime maxTime
. selectPeerSelectionTraceEvents
. runGovernorInMockEnvironment
$ env
govPublicRootPeersSig :: Signal (Set PeerAddr)
govPublicRootPeersSig =
selectGovState (PublicRootPeers.toSet . Governor.publicRootPeers)
events
govEstablishedPeersSig :: Signal (Set PeerAddr)
govEstablishedPeersSig =
selectGovState
(EstablishedPeers.toSet . Governor.establishedPeers)
events
govInProgressPromoteColdSig :: Signal (Set PeerAddr)
govInProgressPromoteColdSig =
selectGovState
Governor.inProgressPromoteCold
events
publicInEstablished :: Signal Bool
publicInEstablished =
(\publicPeers established inProgressPromoteCold ->
Set.size
(publicPeers `Set.intersection`
(established `Set.union` inProgressPromoteCold))
> 0
) <$> govPublicRootPeersSig
<*> govEstablishedPeersSig
<*> govInProgressPromoteColdSig
meaning :: Bool -> String
meaning False = "No PublicPeers in Established Set"
meaning True = "PublicPeers in Established Set"