Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix a potential space leak related to HasCallStack quirks #279

Merged
merged 1 commit into from
Nov 24, 2024

Conversation

arybczak
Copy link
Member

The following program:

import Control.Monad
import Effectful
import Effectful.Concurrent
import Effectful.Concurrent.MVar
import Effectful.Reader.Dynamic
import Effectful.Provider
import Effectful.Provider.List

f :: Concurrent :> es => MVar () -> Int -> Eff es ()
f var = \case
  0 -> putMVar var ()
  n -> void $ forkIO $ f var (n - 1)

main :: IO ()
main = runEff
  . runReader ()
  . runProvider_ (\() -> runReader ())
  . runProviderList_ @'[Reader ()] (\() -> runReader ())
  . runConcurrent $ do
  var <- newEmptyMVar
  f var 10000000
  takeMVar var

used to leak memory because GHC attaches a new stack frame to fields with HasCallStack constraints on every record reconstruction. Here it means every relinking, so if the relinks are nested, call stacks atached to these fields will keep growing.

The workaround is to wrap these fields in newtypes, see https://gitlab.haskell.org/ghc/ghc/-/issues/25520 for more information.

The following program:

```haskell
import Control.Monad
import Effectful
import Effectful.Concurrent
import Effectful.Concurrent.MVar
import Effectful.Reader.Dynamic
import Effectful.Provider
import Effectful.Provider.List

f :: Concurrent :> es => MVar () -> Int -> Eff es ()
f var = \case
  0 -> putMVar var ()
  n -> void $ forkIO $ f var (n - 1)

main :: IO ()
main = runEff
  . runReader ()
  . runProvider_ (\() -> runReader ())
  . runProviderList_ @'[Reader ()] (\() -> runReader ())
  . runConcurrent $ do
  var <- newEmptyMVar
  f var 10000000
  takeMVar var
```

used to leak memory because GHC attaches a new stack frame to fields with
HasCallStack constraints on every record reconstruction. Here it means every
relinking, so if the relinks are nested, call stacks atached to these fields
will keep growing.

The workaround is to wrap these fields in newtypes, see
https://gitlab.haskell.org/ghc/ghc/-/issues/25520 for more information.
@arybczak arybczak merged commit 1126e23 into master Nov 24, 2024
8 checks passed
@arybczak arybczak deleted the fix-call-stack-space-leak branch November 24, 2024 14:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant