ruby / ruby/json

Is JSON::Coder intended to be thread safe ?

Open
#1,064 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Ruby
Stars
782
Forks
383
Avg merge
1d 18h
Merged PRs (30d)
10

Description

In JRuby we hit a race condition: ActiveSupport uses a single shared JSON::Coder
instance and calls #dump on it from multiple threads.

ActiveSupport creates one shared Coder:
https://github.com/rails/rails/blob/v8.1.3.1/activesupport/lib/active_support/json/encoding.rb#L152

…and reuses it on every encode:
https://github.com/rails/rails/blob/v8.1.3.1/activesupport/lib/active_support/json/encoding.rb#L188

The error we got, on a flat object was

JSON::NestingError: nesting of 100 is too deep. Did you try to serialize objects with circular references?

Question: is a single JSON::Coder instance intended to be safe to call
concurrently from multiple threads (i.e. is #dump/#generate on one Coder
intended to be thread-safe)?

Versions: json 2.21.2 (java), JRuby 10.0.5.0, activesupport 8.1.3.1.

I have a small threaded reproduction I can add if useful.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with activesupport/lib/active_support/json/encoding.rb at the shared JSON::Coder creation and reuse points, then inspect JSON::Coder#dump and #generate for concurrent behavior on JRuby. Use the reported threaded reproduction, if provided, to confirm the race; done means the thread-safety contract is decided and the behavior is documented or covered by a regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
json, ruby
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.