Skip to content

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

Merged
jwils merged 1 commit into
mainfrom
joshuaw/threadsafe-validator-caches
Nov 24, 2026
Merged

jwils merged 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>
@jwils
jwils merged commit 1f7d383 into main Nov 24, 2026
24 checks passed
@jwils
jwils deleted the joshuaw/threadsafe-validator-caches branch November 24, 2026 17:57
myronmarston added a commit that referenced this pull request Nov 24, 2026
On JRuby, concurrent writes to a plain `Hash` can lose entries. #1469
guarded 2 lazily populated caches with inline mutexes. 7 more caches
have the same race: each lives on an object built once per process and
gets entries while events are indexed or GraphQL requests run. This PR
adds one shared cache type, uses it for those 7, and switches #1469's 2
caches to it.

## Summary

```ruby
# elasticgraph-support: Support::ThreadSafeCache
def fetch_or_store(key)
  @monitor.synchronize do
    @values_by_key.fetch(key) { @values_by_key[key] = yield }
  end
end
```

- **Reentrant lock:** a `Monitor`, not a `Mutex`. `Schema#type_from`
builds a `Type`, and that build calls `type_from` for the wrapped type
while the lock is held.
- **`nil` and `false` are cached:** `fetch` checks `key?`, so a cached
falsy value doesn't trigger a rebuild, as it would with `||=`.

| Cache | Path |
| --- | --- |
| `JSONSchema::ValidatorFactory#validator_for` (#1469) | indexing |
| `JSONIngestion::EnvelopeValidator` validator factories (#1469) |
indexing |
| `JSONIngestion::RecordPreparerFactory#for_json_schema_version` |
indexing |
| `SchemaArtifacts::FromDisk#json_schemas_for` | indexing |
| `RuntimeMetadata::ExtensionLoader#load` | indexing |
| `IndexDefinition::Base#list_counts_field_paths_for_source` | indexing
|
| `GraphQL::Schema#type_from` | GraphQL |
| `GraphQL::Schema::Type#enum_value_named` | GraphQL |

`RecordPreparerFactory` used to load each scalar type's indexing
preparer lazily. Now it builds that map in its constructor, because the
scalar types are known then. A misconfigured preparer therefore fails at
boot, not on the first event that uses it.

## Evidence

`thread_safe_cache_spec.rb` runs a deterministic race. The test holds
thread 1 inside the block until thread 2 is asleep, then counts block
calls.

- **Before:** the stub had no lock and used `||=`. Two examples failed:
"evaluates the block only once when another thread requests the same
key..." (`expected: 1, got: 2`), and "caches `nil` and `false` values"
(`expected: 2, got: 4`).
- **After:** all examples pass, including the test where the block
fetches a different key from the same cache.

Per-gem suites (support, schema_artifacts, json_ingestion,
datastore_core, graphql, indexer) pass with 100% line and branch
coverage. Steep is clean.

## Merge Danger

**Door:** two-way

**Blast Radius:** small. Every indexed event and every GraphQL request
now acquires an uncontended `Monitor` for each cache it reads.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
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