Skip to content
Merged
4 changes: 4 additions & 0 deletions core/docs/Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@
* Fix `MutArray.appendMax` on a slice returning an array with a capacity
beyond its allocation, appending to it could corrupt memory.
* Fix `MutArray.createMinOf 0` writing beyond its allocation.
* Fix `Fold.bracketIO` losing the input after the inner fold terminates,
and not running the release action if the stream ends there.
* Fix `Fold.finallyIO` running the action only on GC when the inner fold
terminates.

## 0.3.1 (May 2026)

Expand Down
33 changes: 22 additions & 11 deletions core/src/Streamly/Internal/Data/Fold/Exception.hs
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,14 @@ bracketIO bef aft bet = Fold step initial extract final
res <- initial1
case res of
Partial s -> do
s1 <- step1 s a `MC.onException` liftIO (runIOFinalizer ref)
let fld1 = Fold step1 (pure s1) extract1 final1
pure $ Partial $ Tuple' ref fld1
r <- step1 s a `MC.onException` liftIO (runIOFinalizer ref)
case r of
Partial s1 -> do
let fld1 = Fold step1 (pure (Partial s1)) extract1 final1
pure $ Partial $ Tuple' ref fld1
Done b -> do
liftIO $ runIOFinalizer ref
pure $ Done b
Done b -> do
liftIO $ runIOFinalizer ref
pure $ Done b
Expand All @@ -156,9 +161,11 @@ bracketIO bef aft bet = Fold step initial extract final
case res of
Partial s -> do
val <- final1 s `MC.onException` liftIO (runIOFinalizer ref)
runIOFinalizer ref
liftIO $ runIOFinalizer ref
pure val
Done b -> pure b
Done b -> do
liftIO $ runIOFinalizer ref
pure b

-- | Run a side effect whenever the fold stops normally, aborts due to an
-- exception or is garbage collected.
Expand All @@ -173,15 +180,19 @@ finallyIO aft (Fold step1 initial1 extract1 final1) =
initial = do
ref <- liftIO $ newIOFinalizer aft
res <- initial1 `MC.onException` liftIO (runIOFinalizer ref)
pure $ case res of
Done b -> Done b
Partial s -> Partial $ Tuple' ref s
case res of
Done b -> do
liftIO $ runIOFinalizer ref
pure $ Done b
Partial s -> pure $ Partial $ Tuple' ref s

step (Tuple' ref s) a = do
res <- step1 s a `MC.onException` liftIO (runIOFinalizer ref)
pure $ case res of
Done b -> Done b
Partial s1 -> Partial $ Tuple' ref s1
case res of
Done b -> do
liftIO $ runIOFinalizer ref
pure $ Done b
Partial s1 -> pure $ Partial $ Tuple' ref s1

extract (Tuple' ref s) =
extract1 s `MC.onException` liftIO (runIOFinalizer ref)
Expand Down
13 changes: 7 additions & 6 deletions core/src/Streamly/Internal/Data/Fold/Type.hs
Original file line number Diff line number Diff line change
Expand Up @@ -905,7 +905,7 @@ toListRev = foldl' (flip (:)) []
-- | Buffers the input stream to a pure stream in the reverse order of the
-- input.
--
-- >>> toStreamKRev = Foldable.foldl' (flip StreamK.cons) StreamK.nil
-- >>> toStreamKRev = Fold.foldl' (flip StreamK.cons) StreamK.nil
--
-- This is more efficient than 'toStreamK'. toStreamK has exactly the same
-- performance as reversing the stream after toStreamKRev.
Expand All @@ -921,7 +921,7 @@ toStreamKRev = fromScanl Scanl.toStreamKRev

-- | A fold that buffers its input to a pure stream.
--
-- >>> toStreamK = foldr StreamK.cons StreamK.nil
-- >>> toStreamK = Fold.foldr' StreamK.cons StreamK.nil
-- >>> toStreamK = fmap StreamK.reverse Fold.toStreamKRev
--
-- /Internal/
Expand Down Expand Up @@ -1843,7 +1843,7 @@ foldMaybes (Fold step1 initial1 extract1 final1) =

initial = fmap Just <$> initial1

step _ Nothing = pure $ Done Nothing
step st Nothing = Done Nothing <$ final1 st
step st (Just x) = fmap Just <$> step1 st x

extract st = Just <$> extract1 st
Expand All @@ -1870,7 +1870,7 @@ foldEithers (Fold step1 initial1 extract1 final1) =

initial = fmap Right <$> initial1

step _ (Left x) = pure $ Done (Left x)
step st (Left x) = Done (Left x) <$ final1 st
step st (Right x) = fmap Right <$> step1 st x

extract st = Right <$> extract1 st
Expand Down Expand Up @@ -2579,15 +2579,16 @@ refoldMany1
Partial s -> cextract s
Done b -> return b

-- | Extract the output of a fold and refold it using a 'Refold'.
-- | Finalize a fold without any input and use its output as the initial
-- value of a 'Refold'.
--
-- A fusible alternative to 'concatMap'.
--
-- /Internal/
{-# INLINE refold #-}
refold :: Monad m => Refold m b a c -> Fold m a b -> Fold m a c
refold (Refold step inject extract) f =
Fold step (extractM f >>= inject) extract extract
Fold step (finalM f >>= inject) extract extract

------------------------------------------------------------------------------
-- morphInner
Expand Down
6 changes: 3 additions & 3 deletions core/src/Streamly/Internal/Data/RingArray.hs
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ decrHeadByOffset rh rs n =
-- the prev (older) item, when the ring head is at the oldest item it will move
-- to the newest item.
--
-- >>> moveForward = RingArray.moveBy (-1)
-- >>> moveReverse = RingArray.moveBy (-1)
--
{-# INLINE moveReverse #-}
moveReverse :: forall a. Unbox a => RingArray a -> RingArray a
Expand Down Expand Up @@ -399,7 +399,7 @@ replace :: forall m a. (MonadIO m, Unbox a) => RingArray a -> a -> m (RingArray
replace rb newVal = do
-- Note: ring size cannot be zero.
when (ringSize rb == 0) $
error "insert: cannot insert in 0 sized ring"
error "replace: cannot replace in 0 sized ring"
old <- unsafeGetRawIndex (ringHead rb) rb
liftIO $ pokeAt (ringHead rb) (ringContents rb) newVal
pure (moveForward rb, old)
Expand Down Expand Up @@ -683,7 +683,7 @@ eqArrayN RingArray{..} Array.Array{..} nBytes
eqArray :: RingArray a -> Array a -> IO Bool
eqArray RingArray{..} Array.Array{..}
| arrEnd - arrStart < ringSize =
error "eqArrayN: array is shorter than ring"
error "eqArray: array is shorter than ring"
| otherwise = do
part1 <-
MutByteArray.unsafeByteCmp
Expand Down
8 changes: 6 additions & 2 deletions core/src/Streamly/Internal/Data/RingArray/Generic.hs
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,12 @@ copyToMutArray adj n RingArray{..} = do
end = idx + len
arr <- MutArray.emptyOf len
arr1 <- MutArray.uninit arr len
MutArray.unsafePutSlice ringArr idx arr1 0 (ringMax - idx)
MutArray.unsafePutSlice ringArr 0 arr1 (ringMax - idx) (end - ringMax)
if end <= ringMax
then MutArray.unsafePutSlice ringArr idx arr1 0 len
else do
MutArray.unsafePutSlice ringArr idx arr1 0 (ringMax - idx)
MutArray.unsafePutSlice
ringArr 0 arr1 (ringMax - idx) (end - ringMax)
return arr1

-- This would be theoretically slower than toMutArray because of a branch
Expand Down
10 changes: 9 additions & 1 deletion core/src/Streamly/Internal/Data/Serialize/TH.hs
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,15 @@ mkDeserializeExpr True False headTy tyOfTy =
$(varE _initialOffset)
$(varE _arr)
$(varE _endOffset)
$(multiIfE (map (guardCon conLen off1) cons ++ [catchAll]))|]
-- xorCmp reads the constructor name without bounds checks, so
-- check that the name fits in the buffer before calling it.
if $(varE off1) + w8_int $(varE conLen) > $(varE _endOffset)
then error
("deserializeAt: constructor name at offset = "
++ show $(varE off1)
++ " exceeds the buffer length = "
++ show $(varE _endOffset))
else $(multiIfE (map (guardCon conLen off1) cons ++ [catchAll]))|]

catchAll =
normalGE
Expand Down
6 changes: 5 additions & 1 deletion core/src/Streamly/Internal/Data/Serialize/TH/RecHeader.hs
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,11 @@ mkRecDeserializeExpr initialOff endOff deserializeWithKeys con = do
deserializeAt $(varE initialOff) $(varE _arr) $(varE endOff)
($(varP hOff), hlen1 :: Word32) <-
deserializeAt hlenOff $(varE _arr) $(varE endOff)
if (hlen1 == $(litIntegral hlen)) && $(xorCmp hval hOff _arr)
-- xorCmp reads the header without bounds checks, so check that the
-- header fits in the buffer before calling it.
if (hlen1 == $(litIntegral hlen))
&& $(varE hOff) + $(litIntegral hlen) <= $(varE endOff)
&& $(xorCmp hval hOff _arr)
then do
let $(varP (makeI 0)) =
$(varE initialOff) +
Expand Down
39 changes: 39 additions & 0 deletions test/Streamly/Test/Data/Fold/Exception.hs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,20 @@ finallyIOFold = do
val <- readIORef ref
val `shouldBe` 1

finallyIOInnerDone :: Expectation
finallyIOInnerDone = do
ref <- newIORef (0 :: Int)
let fld = Fold.finallyIO (writeIORef ref 1) (Fold.take 1 Fold.drain)
Stream.fold fld (Stream.fromList [1,2,3 :: Int])
readIORef ref `shouldReturn` 1

finallyIOInitDone :: Expectation
finallyIOInitDone = do
ref <- newIORef (0 :: Int)
let fld = Fold.finallyIO (writeIORef ref 1) (Fold.take 0 Fold.drain)
Stream.fold fld (Stream.fromList [1 :: Int])
readIORef ref `shouldReturn` 1

bracketIOFold :: Expectation
bracketIOFold = do
ref <- newIORef (0 :: Int)
Expand All @@ -49,6 +63,27 @@ bracketIOFold = do
val <- readIORef ref
val `shouldBe` 2

-- The fold must stop with the inner fold, without consuming another input,
-- and release the resource.
bracketIOInnerDone :: Expectation
bracketIOInnerDone = do
ref <- newIORef (0 :: Int)
let fld = Fold.bracketIO (return ()) (\_ -> writeIORef ref 1)
(\_ -> Fold.take 2 Fold.toList)
(r, rest) <- Stream.foldBreak fld (Stream.fromList [1..5 :: Int])
r `shouldBe` [1,2]
Stream.toList rest `shouldReturn` [3,4,5]
readIORef ref `shouldReturn` 1

bracketIOInnerDoneAtEnd :: Expectation
bracketIOInnerDoneAtEnd = do
ref <- newIORef (0 :: Int)
let fld = Fold.bracketIO (return ()) (\_ -> writeIORef ref 1)
(\_ -> Fold.take 2 Fold.toList)
r <- Stream.fold fld (Stream.fromList [1,2 :: Int])
r `shouldBe` [1,2]
readIORef ref `shouldReturn` 1

onExceptionFold :: Expectation
onExceptionFold = do
ref <- newIORef (0 :: Int)
Expand All @@ -71,5 +106,9 @@ main = hspec $ do
describe moduleName $ do
it "before" beforeFold
it "finallyIO" finallyIOFold
it "finallyIO inner fold done" finallyIOInnerDone
it "finallyIO inner fold done in initial" finallyIOInitDone
it "bracketIO" bracketIOFold
it "bracketIO inner fold done" bracketIOInnerDone
it "bracketIO inner fold done at end" bracketIOInnerDoneAtEnd
it "onException" onExceptionFold
42 changes: 41 additions & 1 deletion test/Streamly/Test/Data/Fold/Type.hs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ module Streamly.Test.Data.Fold.Type

import Control.Exception (SomeException, evaluate, try)
import Data.Functor.Identity (Identity(..), runIdentity)
import Data.IORef (newIORef, readIORef, modifyIORef')
import Data.IORef (IORef, newIORef, readIORef, modifyIORef')
import qualified Streamly.Internal.Data.Fold as Fold
import qualified Streamly.Internal.Data.Fold as F
import qualified Streamly.Internal.Data.Refold.Type as Refold
import qualified Streamly.Internal.Data.Scanl as Scanl
import qualified Streamly.Internal.Data.Stream as Stream

Expand Down Expand Up @@ -408,6 +409,31 @@ foldEithers = do
(Stream.fromList [Right 1, Right 2, Right 3 :: Either String Int])
r `shouldBe` Right 6

-- | A fold whose final sets the IORef to True.
finalSetsRef :: IORef Bool -> Fold.Fold IO Int ()
finalSetsRef ref =
Fold.Fold
(\s _ -> return (Fold.Partial s))
(return (Fold.Partial ()))
return
(\_ -> modifyIORef' ref (const True))

foldMaybesFinal :: Expectation
foldMaybesFinal = do
ref <- newIORef False
Stream.fold (Fold.foldMaybes (finalSetsRef ref))
(Stream.fromList [Just 1, Nothing])
`shouldReturn` Nothing
readIORef ref `shouldReturn` True

foldEithersFinal :: Expectation
foldEithersFinal = do
ref <- newIORef False
Stream.fold (Fold.foldEithers (finalSetsRef ref))
(Stream.fromList [Right 1, Left "e" :: Either String Int])
`shouldReturn` Left "e"
readIORef ref `shouldReturn` True

-------------------------------------------------------------------------------
-- Condition
-------------------------------------------------------------------------------
Expand Down Expand Up @@ -469,6 +495,17 @@ groupsOf = do
-- Nested application
-------------------------------------------------------------------------------

-- | 'Fold.refold' must finalize the source fold, not extract it. The
-- 'Fold.splitWith' fold has no extract.
refoldFinal :: Expectation
refoldFinal = do
let src =
Fold.splitWith (++)
(Fold.fromPure [1]) (Fold.take 1 (Fold.foldl' (++) []))
Stream.fold (Fold.refold Refold.sconcat src)
(Stream.fromList [[2 :: Int]])
`shouldReturn` [1,2]

concatMap :: Expectation
concatMap = do
r <- Stream.fold
Expand Down Expand Up @@ -683,13 +720,16 @@ main = hspec $ do

it "foldMaybes" foldMaybes
it "foldEithers" foldEithers
it "foldMaybes calls final" foldMaybesFinal
it "foldEithers calls final" foldEithersFinal
it "ifThen" ifThen
it "split_" split_
prop "many" many
it "manyPost" manyPost
it "groupsOf" groupsOf
it "concatMap" concatMap
it "duplicate" duplicate
it "refold calls final" refoldFinal
prop "teeWithFstLength" teeWithFstLength
prop "teeWithMinLength1" teeWithMinLength1
prop "teeWithMinLength2" teeWithMinLength2
Expand Down
10 changes: 10 additions & 0 deletions test/Streamly/Test/Data/RingArray/Generic.hs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,15 @@ testCopyToMutArray = do
_ <- RingArray.unsafeInsertRingWith rng 99
MutArray.toList marr `shouldReturn` [3, 4, 5]

-- Copy fewer elements than the ring has, without wrapping around.
testCopyToMutArrayPartial :: IO ()
testCopyToMutArrayPartial = do
rng <- fromListLastN 5 [1 .. 5 :: Int]
marr <- RingArray.copyToMutArray 0 2 rng
MutArray.toList marr `shouldReturn` [1, 2]
marr1 <- RingArray.copyToMutArray 1 3 rng
MutArray.toList marr1 `shouldReturn` [2, 3, 4]

testCopyToMutArrayEmpty :: IO ()
testCopyToMutArrayEmpty = do
rng <- RingArray.emptyOf 0 :: IO (RingArray Int)
Expand Down Expand Up @@ -183,4 +192,5 @@ main = hspec $ do
it "toMutArray (wrap around)" testToMutArrayWrap
it "toMutArray (empty ring)" testToMutArrayEmpty
it "copyToMutArray" testCopyToMutArray
it "copyToMutArray (partial)" testCopyToMutArrayPartial
it "copyToMutArray (empty ring)" testCopyToMutArrayEmpty
Loading