Skip to content

Commit 2dc5ada

Browse files
authored
Handle process deaths without scanning unrelated monitors and connections (haskell-distributed#495)
* Benchmarks: process deaths with many unrelated monitors or connections The cost of a process death should not depend on the monitors and connections of other processes on the node. Measure it with 0, 1,000 and 10,000 of each. * Node controller: find the links and monitors a death affects by key range ncEffectDied scanned all links and monitors of the node on every death (splitNotif used partitionWithKeyBy1st with impliesDeathOf), for a node death also all watchers, and it rebuilt registeredOnNodes. So each death took time proportional to all monitors and links of the node, and local sends, which also go through the node controller, waited behind it. Add deathKey, a monotone projection of identifiers such that impliesDeathOf a b if and only if deathKey a b is in deathKeys a. The identifiers that die with a are then a few ranges of keys, which the new BiMultiMap.partitionOn finds with Map.spanAntitone in time polylogarithmic in the size of the map, plus the size of the result. ncEffectDied still scans registeredHere, which is keyed by name. In the deaths benchmark, a process death with 10,000 unrelated monitors on the node went from about 2,900 to 45 µs (about 15 µs with none). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Process exit: remove the process's connections by key range cleanupProcess scanned all of localConnections on every process exit. The result is part of the node state, which local and remote sends, spawns and the node controller also use. Connections are keyed by (from, to), so the connections of the process and its typed channels are found with partitionOn and deathKey. In the deaths benchmark, a process death with 10,000 unrelated connections on the node went from about 2,300 to 37 µs (about 15 µs with none). * Address review: version 0.7.10, @SInCE, move IdentifierKind - Bump distributed-process to 0.7.10, and require it in TestDeathKeys. - Add @SInCE 0.7.10 to the new exports of BiMultiMap and Messaging. - Move IdentifierKind and identifierKind to Messaging, next to deathKey, their only user.
1 parent 3067241 commit 2dc5ada

9 files changed

Lines changed: 333 additions & 33 deletions

File tree

‎packages/distributed-process-tests/distributed-process-tests.cabal‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,3 +193,18 @@ Test-Suite TestMxInTCP
193193
default-language: Haskell98
194194
ghc-options: -threaded -rtsopts -with-rtsopts=-N -fno-warn-unused-do-bind
195195
HS-Source-Dirs: tests
196+
197+
Test-Suite TestDeathKeys
198+
import: warnings
199+
Type: exitcode-stdio-1.0
200+
Main-Is: TestDeathKeys.hs
201+
Build-Depends: base >= 4.14 && < 5,
202+
bytestring >= 0.10 && < 0.13,
203+
containers >= 0.6 && < 0.9,
204+
distributed-process >= 0.7.10 && < 0.8,
205+
network-transport >= 0.4.1.0 && < 0.6,
206+
tasty >= 1.5 && <1.6,
207+
tasty-hunit >=0.10 && <0.11,
208+
tasty-quickcheck >=0.11 && <0.12
209+
default-language: Haskell2010
210+
HS-Source-Dirs: tests
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
module Main where
2+
3+
import Control.Distributed.Process.Internal.BiMultiMap (BiMultiMap)
4+
import qualified Control.Distributed.Process.Internal.BiMultiMap as BiMultiMap
5+
import Control.Distributed.Process.Internal.Messaging
6+
( deathKey
7+
, deathKeys
8+
, impliesDeathOf
9+
)
10+
import Control.Distributed.Process.Internal.Types
11+
( Identifier(..)
12+
, LocalProcessId(..)
13+
, NodeId(..)
14+
, ProcessId(..)
15+
, SendPortId(..)
16+
)
17+
import qualified Data.ByteString.Char8 as BSC
18+
import Data.Map (Map)
19+
import qualified Data.Map as Map
20+
import Data.Set (Set)
21+
import Network.Transport (EndPointAddress(..))
22+
import Test.Tasty (TestTree, defaultMain, testGroup)
23+
import Test.Tasty.HUnit (assertEqual, testCase)
24+
import Test.Tasty.QuickCheck
25+
( Arbitrary(..)
26+
, Positive(..)
27+
, elements
28+
, testProperty
29+
)
30+
31+
-- All identifiers with 2 nodes, 4 processes per node and 2 ports per process.
32+
universe :: [Identifier]
33+
universe = map NodeIdentifier nodes
34+
++ map ProcessIdentifier processes
35+
++ [ SendPortIdentifier (SendPortId pid c) | pid <- processes, c <- [0, 1] ]
36+
where
37+
nodes = [ NodeId (EndPointAddress (BSC.pack a)) | a <- ["a", "b"] ]
38+
processes = [ ProcessId nid (LocalProcessId u c)
39+
| nid <- nodes, u <- [0, 1], c <- [0, 1] ]
40+
41+
newtype Ident = Ident Identifier
42+
43+
instance Show Ident where
44+
show (Ident i) = show i
45+
46+
instance Arbitrary Ident where
47+
arbitrary = Ident <$> elements universe
48+
49+
testDeathKeyImpliesDeathOf :: TestTree
50+
testDeathKeyImpliesDeathOf =
51+
testCase "deathKey agrees with impliesDeathOf" $
52+
assertEqual "counterexamples" []
53+
[ (a, b) | a <- universe, b <- universe
54+
, (a `impliesDeathOf` b) /= (deathKey a b `elem` deathKeys a) ]
55+
56+
testDeathKeyMonotone :: TestTree
57+
testDeathKeyMonotone =
58+
testCase "deathKey is monotone" $
59+
assertEqual "counterexamples" []
60+
[ (a, b1, b2) | a <- universe, b1 <- universe, b2 <- universe
61+
, b1 <= b2, deathKey a b1 > deathKey a b2 ]
62+
63+
-- Projections on Int: @(`div` d)@ is monotone.
64+
prop_partitionOn :: Positive Int -> [Int] -> Map Int Char -> Bool
65+
prop_partitionOn (Positive d) ps m =
66+
BiMultiMap.partitionOn (`div` d) ps m
67+
== Map.partitionWithKey (\k _ -> (k `div` d) `elem` ps) m
68+
69+
prop_partitionOnDeathKey :: Ident -> [(Ident, Char)] -> Bool
70+
prop_partitionOnDeathKey (Ident a) kvs =
71+
BiMultiMap.partitionOn (deathKey a) (deathKeys a) m
72+
== Map.partitionWithKey (\k _ -> a `impliesDeathOf` k) m
73+
where
74+
m = Map.fromList [ (k, v) | (Ident k, v) <- kvs ]
75+
76+
prop_partitionOnBy1st :: Positive Int -> [Int] -> [(Int, Int, Char)] -> Bool
77+
prop_partitionOnBy1st (Positive d) ps ts =
78+
sameResult (BiMultiMap.partitionOnBy1st (`div` d) ps bm)
79+
(BiMultiMap.partitionWithKeyBy1st (\k _ -> (k `div` d) `elem` ps) bm)
80+
where
81+
bm = fromTriplets ts
82+
83+
prop_partitionOnBy2nd :: Positive Int -> [Int] -> [(Int, Int, Char)] -> Bool
84+
prop_partitionOnBy2nd (Positive d) ps ts =
85+
sameResult (BiMultiMap.partitionOnBy2nd (`div` d) ps bm)
86+
(BiMultiMap.partitionWithKeyBy2nd (\k _ -> (k `div` d) `elem` ps) bm)
87+
where
88+
bm = fromTriplets ts
89+
90+
sameResult :: (Eq k, Eq s)
91+
=> (Map k s, BiMultiMap Int Int Char)
92+
-> (Map k s, BiMultiMap Int Int Char)
93+
-> Bool
94+
sameResult (m, bm) (m', bm') = m == m' && sides bm == sides bm'
95+
96+
fromTriplets :: [(Int, Int, Char)] -> BiMultiMap Int Int Char
97+
fromTriplets = foldr (\(a, b, v) -> BiMultiMap.insert a b v) BiMultiMap.empty
98+
99+
-- Both sides of a multimap: by the first and by the second component.
100+
sides :: BiMultiMap Int Int Char
101+
-> (Map Int (Set (Int, Char)), Map Int (Set (Int, Char)))
102+
sides bm = ( fst (BiMultiMap.partitionWithKeyBy1st (\_ _ -> True) bm)
103+
, fst (BiMultiMap.partitionWithKeyBy2nd (\_ _ -> True) bm)
104+
)
105+
106+
main :: IO ()
107+
main = defaultMain tests
108+
109+
tests :: TestTree
110+
tests = testGroup "Death keys"
111+
[ testDeathKeyImpliesDeathOf
112+
, testDeathKeyMonotone
113+
, testProperty "partitionOn" prop_partitionOn
114+
, testProperty "partitionOn with deathKey" prop_partitionOnDeathKey
115+
, testProperty "partitionOnBy1st" prop_partitionOnBy1st
116+
, testProperty "partitionOnBy2nd" prop_partitionOnBy2nd
117+
]

‎packages/distributed-process/ChangeLog‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
1+
Unreleased
2+
3+
* The node controller handles the death of a node, process or typed channel in
4+
time that depends on the number of links and monitors it affects, not on
5+
their total number.
6+
* A process exit takes time that depends on the number of connections of
7+
the process, not on the number of connections of the node.
8+
19
2026-09-21 Laurent P. René de Cotret <laurent.decotret@outlook.com> 0.7.9
210

311
* `receiveTimeout`, `expectTimeout` and `receiveChanTimeout` now arm the

‎packages/distributed-process/benchmarks/Main.hs‎

Lines changed: 70 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ import Control.Distributed.Process.Node
102102
)
103103
import Control.Distributed.Process.Serializable (Serializable)
104104
import qualified Control.Exception as E
105-
import Control.Monad (forever, replicateM, replicateM_, void, when)
105+
import Control.Monad (forM_, forever, replicateM, replicateM_, void, when)
106106
import qualified Control.Monad.Catch as Catch
107107
import Data.Binary (Binary)
108108
import qualified Data.ByteString.Char8 as BS
@@ -118,6 +118,7 @@ import Test.Tasty.Bench
118118
bench,
119119
bgroup,
120120
defaultMain,
121+
envWithCleanup,
121122
whnfIO,
122123
)
123124

@@ -165,7 +166,8 @@ benchmarks fx =
165166
introspection fx,
166167
ring fx
167168
],
168-
remote fx
169+
remote fx,
170+
deaths fx
169171
]
170172

171173
-- | Cost of the harness alone, and so the floor below which the other numbers
@@ -416,11 +418,7 @@ monitoring fx =
416418
(getSelfNode >>= monitorNode) >>= unmonitor,
417419
repsBench fx "monitorPort/unmonitor" 100 $
418420
monitorPort (fst (fxChan fx)) >>= unmonitor,
419-
repsBench fx "notification (normal exit)" 100 $ do
420-
pid <- spawnLocal (expect :: Process ())
421-
ref <- monitor pid
422-
send pid ()
423-
awaitDown ref,
421+
repsBench fx "notification (normal exit)" 100 exitAndAwait,
424422
repsBench fx "notification (kill)" 100 $ do
425423
pid <- spawnLocal (expect :: Process ())
426424
ref <- monitor pid
@@ -577,6 +575,71 @@ remote fx =
577575
echo = fxRemoteEcho fx
578576
nid = fxRemoteNodeId fx
579577

578+
-- | A process death while the node holds many unrelated monitors or
579+
-- connections. Its cost should not depend on their number.
580+
deaths :: Fixture -> Benchmark
581+
deaths fx =
582+
bgroup
583+
"deaths"
584+
[ bgroup
585+
(show n ++ " " ++ what)
586+
[ envWithCleanup (start fx n) (stopBackground fx) $ \_ ->
587+
repsBench fx "notification (normal exit)" 100 exitAndAwait
588+
]
589+
| (what, start) <-
590+
[ ("monitors", monitoredBackground),
591+
("connections", connectedBackground)
592+
],
593+
n <- [0, 1000, 10000]
594+
]
595+
596+
-- | @n@ idle processes and, first in the list, one process that monitors them.
597+
monitoredBackground :: Fixture -> Int -> IO [ProcessId]
598+
monitoredBackground fx n = runWith fx $ do
599+
us <- getSelfPid
600+
pids <- replicateM n (spawnLocal (expect :: Process ()))
601+
watcher <- spawnLocal $ do
602+
mapM_ monitor pids
603+
send us ()
604+
expect :: Process ()
605+
expect :: Process ()
606+
return (watcher : pids)
607+
608+
-- | @n@ idle processes, each with a connection to the other node.
609+
connectedBackground :: Fixture -> Int -> IO [ProcessId]
610+
connectedBackground fx n = runWith fx $ do
611+
us <- getSelfPid
612+
pids <- replicateM n $ spawnLocal $ do
613+
getSelfPid >>= send (fxRemoteEcho fx)
614+
expect :: Process ()
615+
send us ()
616+
expect :: Process ()
617+
replicateM_ n (expect :: Process ())
618+
return pids
619+
620+
-- | Kills the processes one by one, in order, so that their deaths do not
621+
-- overlap with later benchmarks. Killing the watcher of 'monitoredBackground'
622+
-- first keeps the other deaths cheap.
623+
stopBackground :: Fixture -> [ProcessId] -> IO ()
624+
stopBackground fx pids = fxRun fx $ forM_ pids $ \pid -> do
625+
ref <- monitor pid
626+
kill pid "benchmark done"
627+
awaitDown ref
628+
629+
exitAndAwait :: Process ()
630+
exitAndAwait = do
631+
pid <- spawnLocal (expect :: Process ())
632+
ref <- monitor pid
633+
send pid ()
634+
awaitDown ref
635+
636+
-- | Like 'fxRun', but returns the result.
637+
runWith :: Fixture -> Process a -> IO a
638+
runWith fx act = do
639+
var <- newEmptyMVar
640+
fxRun fx (act >>= liftIO . putMVar var)
641+
takeMVar var
642+
580643
-- | tasty-bench already repeats the body of the benchmark, but the benchmark
581644
-- fixture adds a baseline amount of time which drowns some of the faster benchmarks.
582645
--

‎packages/distributed-process/distributed-process.cabal‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
cabal-version: 3.0
22
Name: distributed-process
3-
Version: 0.7.9
3+
Version: 0.7.10
44
Build-Type: Simple
55
License: BSD-3-Clause
66
License-File: LICENSE

‎packages/distributed-process/src/Control/Distributed/Process/Internal/BiMultiMap.hs‎

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ module Control.Distributed.Process.Internal.BiMultiMap
1212
, deleteAllBy2nd
1313
, partitionWithKeyBy1st
1414
, partitionWithKeyBy2nd
15+
, partitionOnBy1st
16+
, partitionOnBy2nd
17+
, partitionOn
1518
, flip
1619
) where
1720

@@ -100,9 +103,7 @@ partitionWithKeyBy1st :: (Ord a, Ord b, Ord v)
100103
-> (Map a (Set (b, v)), BiMultiMap a b v)
101104
partitionWithKeyBy1st p (BiMultiMap m r) =
102105
let (m0, m1) = Map.partitionWithKey p m
103-
r1 = foldl' (\rr (a, mb) -> reverseDelete a (Set.toList mb) rr) r $
104-
Map.toList m0
105-
in (m0, BiMultiMap m1 r1)
106+
in (m0, BiMultiMap m1 (reverseDeleteAll m0 r))
106107

107108
-- | Like 'partitionWithKeyBy1st' but the predicates takes the second component
108109
-- of the triplets as first argument.
@@ -112,6 +113,42 @@ partitionWithKeyBy2nd :: (Ord a, Ord b, Ord v)
112113
partitionWithKeyBy2nd p b = let (m, b') = partitionWithKeyBy1st p $ flip b
113114
in (m, flip b')
114115

116+
-- | Like 'partitionOn' on the first component of the triplets.
117+
--
118+
-- @since 0.7.10
119+
partitionOnBy1st :: (Ord a, Ord b, Ord v, Ord p)
120+
=> (a -> p) -> [p] -> BiMultiMap a b v
121+
-> (Map a (Set (b, v)), BiMultiMap a b v)
122+
partitionOnBy1st f ps (BiMultiMap m r) =
123+
let (m0, m1) = partitionOn f ps m
124+
in (m0, BiMultiMap m1 (reverseDeleteAll m0 r))
125+
126+
-- | Like 'partitionOn' on the second component of the triplets.
127+
--
128+
-- @since 0.7.10
129+
partitionOnBy2nd :: (Ord a, Ord b, Ord v, Ord p)
130+
=> (b -> p) -> [p] -> BiMultiMap a b v
131+
-> (Map b (Set (a, v)), BiMultiMap a b v)
132+
partitionOnBy2nd f ps b = let (m, b') = partitionOnBy1st f ps $ flip b
133+
in (m, flip b')
134+
135+
-- | @partitionOn f ps m@ is @Map.partitionWithKey (\\k _ -> elem (f k) ps) m@,
136+
-- for a monotone @f@: @k1 <= k2@ implies @f k1 <= f k2@.
137+
--
138+
-- It takes O((length ps + r) * (log n)^2) time for a result of size r, instead
139+
-- of the O(n) of 'Map.partitionWithKey'.
140+
--
141+
-- @since 0.7.10
142+
partitionOn :: (Ord k, Ord p) => (k -> p) -> [p] -> Map k a -> (Map k a, Map k a)
143+
partitionOn f ps m0 = foldl' step (Map.empty, m0) ps
144+
where
145+
step (inside, m) p
146+
| Map.null atP = (inside, m)
147+
| otherwise = (Map.union inside atP, Map.union below above)
148+
where
149+
(below, rest) = Map.spanAntitone ((< p) . f) m
150+
(atP, above) = Map.spanAntitone ((== p) . f) rest
151+
115152
-- | Exchange the first and the second components of all triplets.
116153
flip :: BiMultiMap a b v -> BiMultiMap b a v
117154
flip (BiMultiMap m r) = BiMultiMap r m
@@ -129,6 +166,14 @@ reverseDelete a bs r = foldl' (\rr (b, v) -> Map.update (rmb v) b rr) r bs
129166
where
130167
rmb v = nothingWhen Set.null . Set.delete (a, v)
131168

169+
-- | @reverseDeleteAll m r@ removes from @r@ the triplets of @m@.
170+
--
171+
-- The @r@ map is in reversed form, like in 'reverseDelete'.
172+
reverseDeleteAll :: (Ord a, Ord b, Ord v)
173+
=> Map a (Set (b, v)) -> Map b (Set (a, v)) -> Map b (Set (a, v))
174+
reverseDeleteAll m r =
175+
foldl' (\rr (a, mb) -> reverseDelete a (Set.toList mb) rr) r $ Map.toList m
176+
132177
-- | @nothingWhen p a@ is @Just a@ when @a@ satisfies predicate @p@.
133178
-- Yields @Nothing@ otherwise.
134179
nothingWhen :: (a -> Bool) -> a -> Maybe a

0 commit comments

Comments
 (0)