6 min read
|
Saved February 14, 2026
|
Copied!
Do you care about this?
The article details a puzzling NoMethodError in a Ruby application using the FFI library. It uncovers a critical bug related to garbage collection that can lead to internal Hashes being freed and replaced by Strings, causing runtime errors. The author explores the implications of missing write barriers in the FFI C extension.
If you do, here's more
A developer encountered a baffling error in the Karafka gem, where a `NoMethodError` for a String indicated that an internal Hash had somehow transformed into a String. The issue arose from FFI versions below 1.17.0, which lack proper write barriers, causing Ruby's garbage collector (GC) to free internal Hashes. As a result, the memory previously allocated for a Hash could be reused for a String, leading to the bizarre behavior of the program. The developer faced 2,700 error reports in a single incident, highlighting the severity of the problem.
The investigation began with examining the error's context, particularly at line 112 in the rdkafka-ruby code. The FFI::Struct was correctly defined, and the developer ruled out basic issues like type mismatches and struct alignment. They focused on the internals of Ruby and FFI, discovering that accessing a field in the FFI::Struct relies on a Hash that stores field definitions. If this Hash were freed by the GC, the memory could be repurposed for a String, resulting in the unexpected call to `#default`, a method exclusive to Hashes.
The developer suspected that the use of musl libc in the Docker environment might be a factor, but tests confirmed that struct sizes and alignments were as expected. Ultimately, they connected the dots to the missing write barriers in FFI's C extension. The absence of these barriers led to the GC not recognizing all references, allowing the Hash to be improperly freed. A reproduction script confirmed the issue, showcasing how transient struct classes could lead to similar segfaults, emphasizing the critical need for better memory management practices in the FFI library.
Questions about this article
No questions yet.