Skip to content

Scoped Fiber init - #1379

Merged
ahoy-jon merged 7 commits into
getkyo:mainfrom
johnhungerford:safe-fiber-init
Jul 15, 2025
Merged

ahoy-jon merged 7 commits into
getkyo:mainfrom
johnhungerford:safe-fiber-init

Conversation

@johnhungerford

@johnhungerford johnhungerford commented Jul 14, 2025 •

Copy link
Copy Markdown
Collaborator

Fixes #1167

Problem

By default, Fiber.init forks a fiber without ever guaranteeing it will be interrupted. The result is that fibers can easily end up lost in an application in a permanently suspended or long-running state. It would be good to have a behavior somewhat like ZIO, that guarantees cleanup of fibers

Solution

Following the pattern established by #1168 , we change Fiber.init to introduce the Scope effect, interrupting the forked fiber in the registered finalizer; we add a Fiber.use method to use a forked fiber within a function and clean it up afterwards; and finally, we add Fiber.initUnscoped to produce the previous behavior, which forks a fiber and never guarantees interruptions.

Notes

While this change was inspired by ZIO's behavior, it departs from ZIO in that by default ZIO binds each forked fiber to the parent fiber and interrupts child fiber whenever its parent fiber completes. I chose not to try to reproduce this for two reasons:

  1. It would require some deeper changes to the runtime
  2. I don't actually like ZIO's behavior so much, because it means the behavior of async effects depends on how they are composed. See for instance:
import zio.stream._
import zio._

Unsafe.unsafe { implicit unsafe =>
  val eff1 = for
    fiberA <- (ZIO.sleep(1.second) *> Console.printLine("A")).fork
    fiberB <- (ZIO.sleep(1.second) *> Console.printLine("B")).fork
    _ <- Console.printLine("1")
  yield ()

  val eff2 = eff1 *> (ZIO.sleep(5.seconds) *> Console.printLine("2"))

  val eff3 = eff1.fork *> (ZIO.sleep(5.seconds) *> Console.printLine("3"))

  val eff4 = eff1.fork.flatMap(f => (ZIO.sleep(5.seconds) *> f.join *> Console.printLine("4")))

  Runtime.default.unsafe.run(eff1).getOrThrowFiberFailure()
  Runtime.default.unsafe.run(eff2).getOrThrowFiberFailure()
  Runtime.default.unsafe.run(eff3).getOrThrowFiberFailure()
  Runtime.default.unsafe.run(eff4).getOrThrowFiberFailure()
}

eff1 on its own will just print 1
eff2 will print 1, A, B, 2
eff3 will print 1, 2
eff4 will print 1, 4

If you construct an effect that depends on ephemeral forked tasks, it will behave properly in a test or when used in an application in a forked handler, but when you sequence it other effects it may behave differently.

In conclusion, I think introducing the notion of parent fiber and child fiber makes it harder to reason about the fiber lifecycle than if fibers are just treated the same way as other resources.

@johnhungerford johnhungerford changed the title Updated Fiber init methods Scoped Fiber init Jul 14, 2025
Comment thread README.md
Comment on lines -2387 to +2391
Fiber.init(Math.cos(42).toInt).map(_.get)
Fiber.initUnscoped(Math.cos(42).toInt).map(_.get)

// Avoid handling 'Async' directly
val b: Fiber[Int, Any] < Sync =
Fiber.init(a)
Fiber.initUnscoped(a)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@johnhungerford Fiber.init ? There are a lot of cases where it should be Fiber.init

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 I think we should prefer the scoped versions in the readme

@ahoy-jon

Copy link
Copy Markdown
Collaborator

In conclusion, I think introducing the notion of parent fiber and child fiber makes it harder to reason about the fiber lifecycle than if fibers are just treated the same way as other resources.

💯 but we need to document ways to create some FiberHub, to manage child fibers.

@ahoy-jon ahoy-jon left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

README.md / tests could use Fiber.init more. However, good to go for me.

reduce: Reducible[Abort[E]]
): Fiber[A, reduce.SReduced] < (Sync & S) =
Fiber.init {
Fiber.initUnscoped {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we need to address everything in this PR but, in some cases like this one, it makes more sense to add the pending Scope

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, I'll take a look through and see if there are some obvious other ones to update. I did that with the other two resource safety PRs.

Comment on lines +47 to +53

// Async combinator
case fork @ q"$eff.fork" =>
Patch.replaceTree(fork, s"$eff.forkUnscoped")

case forkScoped @ q"$eff.forkScoped" =>
Patch.replaceTree(forkScoped, s"$eff.fork")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! I need to alter a bit the setup to test from 1.0-RC1 to main. (I will update in another PR)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I was considering adding new rules just for RC1 -> 1.0 but would get a little complicated. Should we have separate rules for each RC?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it's better, and we can keep tests for the last two rules.

Console.printLine("hello").now

val async: Fiber[Nothing, Unit] < Async = Fiber.initUnscoped(Async.defer(Async.defer(Kyo.unit)))
val async: Fiber[Nothing, Unit] < Async = /* Consider using Fiber.init or Fiber.use to guarantee termination */ Fiber.initUnscoped(Async.defer(Async.defer(Kyo.unit)))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will try to rework the rule to be able to do something like

/* Consider using Fiber.init or Fiber.use to guarantee termination */
val async: Fiber[Nothing, Unit] < Async = Fiber.initUnscoped(Async.defer(Async.defer(Kyo.unit)))

@ahoy-jon

Copy link
Copy Markdown
Collaborator

@johnhungerford build is failing
> sbt scalafmtSbt

@ahoy-jon
ahoy-jon merged commit 6b4621d into getkyo:main Jul 15, 2025
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.

[feature]: Scoped fibers

3 participants