Skip to content

Do not unlock an output buffer locked by another thread - #187

Open
hsbt wants to merge 4 commits into
masterfrom
claude/zstream-locktmp-168fb3
Open

hsbt wants to merge 4 commits into
masterfrom
claude/zstream-locktmp-168fb3

Conversation

@hsbt

@hsbt hsbt commented Nov 10, 2026

Copy link
Copy Markdown
Member

The temporary lock on the output buffer was taken inside rb_ensure, so when the buffer: given to Zlib::Inflate#inflate was already locked, for example by IO#read in another thread, the failed lock still ran the ensure and released the other thread's lock.

  dict = "dictionary-" * 4
  d = Zlib::Deflate.new
  d.set_dictionary(dict)
  deflated = d.deflate("A" * 12_000, Zlib::FINISH)
  z = Zlib::Inflate.new
  buf = String.new(capacity: 1 << 14)
  z.inflate(deflated, buffer: buf) rescue nil   # Zlib::NeedDict
  z.set_dictionary(dict)
  r, w = IO.pipe
  t = Thread.new { r.read(3, buf) }
  Thread.pass until t.stop?
  z.inflate("", buffer: buf) rescue nil         # fails to lock buf
  w.write("foo")
  t.value
  #=> RuntimeError: temporal unlocking already unlocked string

The failed lock also dropped the pending input, so a retry after the error ended in Zlib::BufError. The input is now put back before the error is raised.

Generated with Claude Code

hsbt and others added 4 commits October 25, 2026 07:59
zstream_run_func took the temporary lock on the output buffer inside rb_ensure, so when the buffer given as `buffer:` was already locked, for example by `IO#read` in another thread, the failed lock still ran the ensure and released that thread's lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A failure of `rb_str_locktmp` escaped `zstream_run_try` before the unconsumed input was put back into the stream, so a retry after the error ended in `Zlib::BufError`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`IO#read` up to Ruby 3.1 resizes a buffer shorter than the read, so `Zlib::Inflate#inflate` failed on the resize before reaching the lock. TruffleRuby's `IO#read` does not lock the buffer at all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
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.

1 participant