fs2 icon indicating copy to clipboard operation
fs2 copied to clipboard

Files[IO].writeAll creates file when it shouldn't

Open nikiforo opened this issue 10 months ago • 1 comments

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
}

nikiforo avatar Jan 19 '26 10:01 nikiforo

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. Since Flags.Write is defined as

Flags(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 flatMap try 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 Stream context, Stream.eval(last) and the writeAll resource acquisition both happen as part of stream evaluation, so by the time last runs, the file from saveNow has already been created. When you shift to F context with last.flatMap(...), last fully evaluates before the stream containing writeAll is 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.

Bhup-GitHUB avatar Feb 08 '26 00:02 Bhup-GitHUB