Skip to content

fix: make JSON schema validator caches thread-safe on JRuby - #1469

Open
jwils wants to merge 1 commit into
mainfrom
joshuaw/threadsafe-validator-caches
Open

jwils wants to merge 1 commit into
mainfrom
joshuaw/threadsafe-validator-caches

Conversation

@jwils

@jwils jwils commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

Follow-up to #1442 (comment).

Two caches on the JSON ingestion path memoize into a Hash.new { |h, k| h[k] = ... } default block without synchronization. On JRuby, concurrent writes to a hash like that can lose entries. The race test in the linked comment saw the wrong cache size in 193 of 200 runs on JRuby 10.0.2 and 0 of 200 on CRuby 4.0.0.

  • Support::JSONSchema::ValidatorFactory#validator_for (@validators_by_type_name)
  • JSONIngestion::EnvelopeValidator#validator (@validator_factories_by_version)

Each cache is now a plain hash, initialized in the constructor and filled under a Mutex with ||=. This matches how #1442's proto RecordPreparer caches its types. The envelope validator also used to create its cache hash lazily with ||=, which was a second race; the hash is now created in initialize. The factory-building logic moved into a private build_validator_factory method, with no change in behavior.

Testing:

  • script/run_gem_specs elasticgraph-support and script/run_gem_specs elasticgraph-json_ingestion pass with 100% line and branch coverage.
  • script/type_check and standardrb on the changed files are clean.

`ValidatorFactory#validator_for` and `EnvelopeValidator#validator` memoized
into `Hash.new { |h, k| h[k] = ... }` caches without synchronization. On JRuby,
concurrent writes to such a hash can lose entries, so threads sharing a
factory or envelope validator could see a corrupted cache.

Guard both caches with a mutex, matching the approach used by the protobuf
record preparer.

Co-authored-by: Josh Wilson <joshuaw@squareup.com>
Signed-off-by: Josh Wilson <joshuaw@squareup.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.

2 participants