The Crystal Programming Language Forum

Finding where a fiber is halt

I was needing to find a reason why a given fiber was hanged. This situation can happen when waiting for IO or Channel operation that seems it will never arrive.

To solve this I, temporally, added the call-stack of the fiber before yielding, so given a Fiber instance I will be able to print where it has stopped.

It was great to have that information so explicitly. Here is the patch I used and a small example.

The example spawn a fiber that need two receive actions two finish. After sending one, the main fiber asks where the spawned fiber f is hanged. The backtrace shows exactly it is on the second receive.

# file:
require "./fiber-debug"

def foo(ch)

def bar(ch)

ch = Channel(Nil).new

f = spawn(name: "worker") do

ch.send nil

# Fiber's backtrace (name: worker):
# in 'resume'
# crystal-0.36.1/src/crystal/ in 'resume'
# crystal-0.36.1/src/ in 'resume'
# crystal-0.36.1/src/crystal/ in 'reschedule'
# crystal-0.36.1/src/crystal/ in 'reschedule'
# crystal-0.36.1/src/ in 'receive'
# in 'bar'    <-- The second ch.receive 🎉🎉🎉
# in 'foo'
# in '->'
# crystal-0.36.1/src/ in 'run'
# crystal-0.36.1/src/ in '->'

ch.send nil

This is the temporal extension I used.

# file:
class Fiber
  property call_stack : Exception::CallStack?

  def print_backtrace
    puts "Fiber's backtrace (name: #{name}):"
    if call_stack = @call_stack
      call_stack.printable_backtrace.each { |l| puts l }
      puts "(running, unable to get backtrace)"

class Crystal::Scheduler
  protected def resume(fiber : Fiber) : Nil
    @current.call_stack =
    @current.call_stack = nil

Thinking in that direction, it would already help to have only the call location for where the execution was yielded (i.e., right? That could even be resolved from magic constants. Thus it would be very lightweight and could perhaps be added to stdlib, maybe behind a debug flag.

That information in this case would’ve been enough, yes. But, the app could be larger and the whole call-stack might be useful. And discarding all the std-lib part of the call-stack is a bit harder, all methods need to pass the last app callee information.

Yeah, I suppose limited usefulness in complex application probably doesn’t make it worth the effort.

But perhaps we could consider adding your extension behind a flag. I’d see that as a useful generic debugging tool.

Great idea. I’ve wanted something similar, it might also be useful for profiling, possibly if all fibers could be enumerated.

ability to retrieve callstacks of all fibers · Issue #4683 · crystal-lang/crystal · GitHub

1 Like