@@ -73,7 +73,7 @@ import Data.Monoid (mempty)
7373import Data.Tree (Forest, Tree (..), drawForest)
7474#endif
7575
76−import Data.WeakBag (WeakBag, WeakBagTicket)
76+import Data.WeakBag (WeakBag, WeakBagTicket, _weakBag_children)
7777import qualified Data.WeakBag as WeakBag
7878#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
7979import Data.Reflection
@@ -1365,7 +1365,17 @@ getRootSubscribed k r sub = do
13651365 , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
13661366#endif
13671367 }
1368− writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "RootSubscribed"
1368+ -- If we die at the same moment that all our children die, they will
1369+ -- try to clean us up but will fail because their Weak reference to us
1370+ -- will also be dead. So, if we are dying, check if there are any
1371+ -- children; since children don't bother cleaning themselves up if
1372+ -- their parents are already dead, I don't think there's a race
1373+ -- condition here. However, if there are any children, then we can
1374+ -- infer that we need to clean ourselves up, so we do.
1375+ finalCleanup = do
1376+ cs <- readIORef $ _weakBag_children subs
1377+ when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)
1378+ writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)
13691379 modifyIORef' (rootSubscribed r) $ DMap.insertWith (error $ "getRootSubscribed: duplicate key inserted into Root") k subscribed --TODO: I think we can just write back mSubscribed rather than re-reading it
13701380 occ <- getOcc
13711381 return (sln, subscribed, occ)