Files[IO].writeAll creates file when it shouldn't
fs2 version: "3.12.2"
import cats.effect.IO
import cats.effect.IOApp
import fs2.Stream
import fs2.io.file.Files
import fs2.io.file.Path
object FilesBugApp extends IOApp.Simple {
def run: IO[Unit] = {
val bytes: Stream[IO, Byte] = Stream.raiseError[IO](new RuntimeException)
bytes.through(Files[IO].writeAll(Path("should-not-be-created"))).compile.drain
}
}
I expect the file not to be created. However, the file is created. This bug also breaks the logic of saving the last file in Stream context. Below is a pseudo-scala description of bug:
val last = Files[F].list("directory").compile.toList.map(_.max)
val saveNow = F.now.flatMap(now => Files[F].writeAll(Path(s"$directory/$now"))))
Stream.eval(last).flatMap(read).map(...).through(saveNow).compile.drain
Here, last always equals to saveNow file. However, if one shifts into F context by removing the Stream.eval the code works as expected.
last.flatMap { file =>
read(file).map(...).through(saveNow).compile.drain
}
Hey @nikiforo I looked into this and here's what's happening.
The writeAll implementation does this internally:
Stream.resource(writeCursor(path, flags)) .flatMap(cursor => cursor.writeAll(in).void.stream)The problem is that
Stream.resource(writeCursor(...))eagerly opens (and creates) the file as part of resource acquisition, before it ever tries to pull a single byte from your input stream. SinceFlags.Writeis defined asFlags(Flag.Write, Flag.Create, Flag.Truncate)the file gets created on disk the moment the resource is acquired.
Only after the file is already created does
flatMaptry to pull from your input stream, which immediately raises the error. The resource finalizer closes the file handle but doesn't delete the file — so you're left with an empty file that shouldn't exist.Same thing explains your second example — when everything is in
Streamcontext,Stream.eval(last)and thewriteAllresource acquisition both happen as part of stream evaluation, so by the timelastruns, the file fromsaveNowhas already been created. When you shift toFcontext withlast.flatMap(...),lastfully evaluates before the stream containingwriteAllis even constructed, so it sees the directory before the new file exists.The fix would be to defer the file creation until the first byte is actually pulled from the input stream, rather than eagerly opening it during resource acquisition.