diff --git a/core/docs/Changelog.md b/core/docs/Changelog.md index 1b3c1f68bb..400d94871a 100644 --- a/core/docs/Changelog.md +++ b/core/docs/Changelog.md @@ -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) diff --git a/core/src/Streamly/Internal/Data/Fold/Exception.hs b/core/src/Streamly/Internal/Data/Fold/Exception.hs index 4e70024600..f002660c9d 100644 --- a/core/src/Streamly/Internal/Data/Fold/Exception.hs +++ b/core/src/Streamly/Internal/Data/Fold/Exception.hs @@ -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 @@ -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. @@ -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) diff --git a/core/src/Streamly/Internal/Data/Fold/Type.hs b/core/src/Streamly/Internal/Data/Fold/Type.hs index f4483755d7..c1604da763 100644 --- a/core/src/Streamly/Internal/Data/Fold/Type.hs +++ b/core/src/Streamly/Internal/Data/Fold/Type.hs @@ -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. @@ -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/ @@ -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 @@ -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 @@ -2579,7 +2579,8 @@ 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'. -- @@ -2587,7 +2588,7 @@ refoldMany1 {-# 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 diff --git a/core/src/Streamly/Internal/Data/RingArray.hs b/core/src/Streamly/Internal/Data/RingArray.hs index 0aff643117..f81572c5b6 100644 --- a/core/src/Streamly/Internal/Data/RingArray.hs +++ b/core/src/Streamly/Internal/Data/RingArray.hs @@ -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 @@ -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) @@ -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 diff --git a/core/src/Streamly/Internal/Data/RingArray/Generic.hs b/core/src/Streamly/Internal/Data/RingArray/Generic.hs index d7a62f66f7..2162bcf8bf 100644 --- a/core/src/Streamly/Internal/Data/RingArray/Generic.hs +++ b/core/src/Streamly/Internal/Data/RingArray/Generic.hs @@ -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 diff --git a/core/src/Streamly/Internal/Data/Serialize/TH.hs b/core/src/Streamly/Internal/Data/Serialize/TH.hs index cc0151124c..3dbc5fa933 100644 --- a/core/src/Streamly/Internal/Data/Serialize/TH.hs +++ b/core/src/Streamly/Internal/Data/Serialize/TH.hs @@ -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 diff --git a/core/src/Streamly/Internal/Data/Serialize/TH/RecHeader.hs b/core/src/Streamly/Internal/Data/Serialize/TH/RecHeader.hs index d21c9cf710..cc925fc053 100644 --- a/core/src/Streamly/Internal/Data/Serialize/TH/RecHeader.hs +++ b/core/src/Streamly/Internal/Data/Serialize/TH/RecHeader.hs @@ -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) + diff --git a/test/Streamly/Test/Data/Fold/Exception.hs b/test/Streamly/Test/Data/Fold/Exception.hs index 25f43fdee1..659f7c070d 100644 --- a/test/Streamly/Test/Data/Fold/Exception.hs +++ b/test/Streamly/Test/Data/Fold/Exception.hs @@ -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) @@ -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) @@ -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 diff --git a/test/Streamly/Test/Data/Fold/Type.hs b/test/Streamly/Test/Data/Fold/Type.hs index 695b7aea1c..4797e66215 100644 --- a/test/Streamly/Test/Data/Fold/Type.hs +++ b/test/Streamly/Test/Data/Fold/Type.hs @@ -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 @@ -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 ------------------------------------------------------------------------------- @@ -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 @@ -683,6 +720,8 @@ 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 @@ -690,6 +729,7 @@ main = hspec $ do it "groupsOf" groupsOf it "concatMap" concatMap it "duplicate" duplicate + it "refold calls final" refoldFinal prop "teeWithFstLength" teeWithFstLength prop "teeWithMinLength1" teeWithMinLength1 prop "teeWithMinLength2" teeWithMinLength2 diff --git a/test/Streamly/Test/Data/RingArray/Generic.hs b/test/Streamly/Test/Data/RingArray/Generic.hs index c06b18617e..093429fd98 100644 --- a/test/Streamly/Test/Data/RingArray/Generic.hs +++ b/test/Streamly/Test/Data/RingArray/Generic.hs @@ -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) @@ -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