Skip to content

Commit 177dff1

Browse files
authored
fix: make lazily populated runtime caches thread-safe (#1470)
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)
1 parent 1f7d383 commit 177dff1

18 files changed

Lines changed: 190 additions & 63 deletions

File tree

‎elasticgraph-datastore_core/lib/elastic_graph/datastore_core/index_definition/base.rb‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
require "elastic_graph/datastore_core/index_config_normalizer"
1010
require "elastic_graph/errors"
1111
require "elastic_graph/support/hash_util"
12+
require "elastic_graph/support/thread_safe_cache"
1213

1314
module ElasticGraph
1415
class DatastoreCore
@@ -126,8 +127,7 @@ def known_related_query_rollover_indices
126127
# on the provided `source` to only contain the paths of fields that are populated by the
127128
# given source.
128129
def list_counts_field_paths_for_source(source)
129-
@list_counts_field_paths_for_source ||= {} # : ::Hash[::String, ::Set[::String]]
130-
@list_counts_field_paths_for_source[source] ||= identify_list_counts_field_paths_for_source(source)
130+
@list_counts_field_paths_for_source.fetch_or_store(source) { identify_list_counts_field_paths_for_source(source) }
131131
end
132132

133133
# The value of the painless `index_data` script's `sourcedFromNestedPaths` param: nested `sourced_from`
@@ -145,6 +145,10 @@ def to_s
145145

146146
private
147147

148+
def after_initialize
149+
@list_counts_field_paths_for_source = Support::ThreadSafeCache.new # : Support::ThreadSafeCache[::String, ::Set[::String]]
150+
end
151+
148152
def identify_list_counts_field_paths_for_source(source)
149153
fields_by_path.filter_map do |path, field|
150154
path if field.source == source && path.split(".").include?(LIST_COUNTS_FIELD)

‎elasticgraph-datastore_core/lib/elastic_graph/datastore_core/index_definition/rollover_index_template.rb‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,8 @@ def related_rollover_index_for_timestamp(timestamp, setting_overrides = {})
135135
private
136136

137137
def after_initialize
138+
super
139+
138140
unless timestamp_field_path && ROLLOVER_SUFFIX_FORMATS_BY_FREQUENCY.key?(frequency)
139141
raise Errors::SchemaError, "Rollover index config 'timestamp_field' or 'frequency' is invalid."
140142
end

‎elasticgraph-datastore_core/sig/elastic_graph/datastore_core/index_definition/base.rbs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,15 @@ module ElasticGraph
99
@accessible_cluster_names_to_index_into: ::Array[::String]?
1010
@known_related_query_rollover_indices: ::Array[RolloverIndex]?
1111
@searches_could_hit_incomplete_docs: bool
12-
@list_counts_field_paths_for_source: ::Hash[::String, ::Set[::String]]
12+
@list_counts_field_paths_for_source: Support::ThreadSafeCache[::String, ::Set[::String]]
1313
@sourced_from_nested_paths_as_painless_param: ::Hash[::String, ::Array[::Hash[::String, ::String]]]?
1414
@max_result_window: ::Integer?
1515

1616
def to_s: () -> ::String
1717

1818
private
1919

20+
def after_initialize: () -> void
2021
def identify_list_counts_field_paths_for_source: (::String) -> ::Set[::String]
2122
end
2223
end

‎elasticgraph-graphql/lib/elastic_graph/graphql/schema.rb‎

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
require "elastic_graph/graphql/query_context"
1313
require "elastic_graph/graphql/schema/field"
1414
require "elastic_graph/graphql/schema/type"
15+
require "elastic_graph/support/thread_safe_cache"
1516

1617
module ElasticGraph
1718
# Wraps a GraphQL::Schema object in order to provide higher-level, more convenient APIs
@@ -42,22 +43,13 @@ def initialize(
4243
@logger = logger
4344
@runtime_metadata = runtime_metadata
4445
@datastore_search_router = datastore_search_router
46+
@index_definitions_by_graphql_type = index_definitions_by_graphql_type
4547

46-
resolvers_needing_lookahead = runtime_metadata.graphql_resolvers_by_name.filter_map do |name, resolver|
48+
@resolvers_needing_lookahead = runtime_metadata.graphql_resolvers_by_name.filter_map do |name, resolver|
4749
name if resolver.needs_lookahead
4850
end.to_set
4951

50-
@types_by_graphql_type = Hash.new do |hash, key|
51-
hash[key] = Type.new(
52-
self,
53-
key,
54-
index_definitions_by_graphql_type[key.graphql_name] || [],
55-
runtime_metadata.object_types_by_name[key.graphql_name],
56-
runtime_metadata.enum_types_by_name[key.graphql_name],
57-
runtime_metadata.scalar_types_by_name[key.graphql_name],
58-
resolvers_needing_lookahead
59-
)
60-
end
52+
@types_by_graphql_type = Support::ThreadSafeCache.new # : Support::ThreadSafeCache[::GraphQL::Schema::_Type, Type]
6153

6254
# Note: as part of loading the schema, the GraphQL gem may use the resolver (such
6355
# when a directive has a custom scalar) so we must wait to instantiate the schema
@@ -107,7 +99,7 @@ def graphql_query_context
10799
end
108100

109101
def type_from(graphql_type)
110-
@types_by_graphql_type[graphql_type]
102+
@types_by_graphql_type.fetch_or_store(graphql_type) { build_type(graphql_type) }
111103
end
112104

113105
# Note: this does not support "wrapped" types (e.g. `Int!` or `[Int]` compared to `Int`),
@@ -193,10 +185,22 @@ def build_base_object_class
193185

194186
def build_types_by_name
195187
graphql_schema.types(visibility_profile: :boot).transform_values do |graphql_type|
196-
@types_by_graphql_type[graphql_type]
188+
type_from(graphql_type)
197189
end
198190
end
199191

192+
def build_type(graphql_type)
193+
Type.new(
194+
self,
195+
graphql_type,
196+
@index_definitions_by_graphql_type[graphql_type.graphql_name] || [],
197+
@runtime_metadata.object_types_by_name[graphql_type.graphql_name],
198+
@runtime_metadata.enum_types_by_name[graphql_type.graphql_name],
199+
@runtime_metadata.scalar_types_by_name[graphql_type.graphql_name],
200+
@resolvers_needing_lookahead
201+
)
202+
end
203+
200204
# Intentionally private: public callers should use `document_types_stored_in` instead.
201205
def indexed_document_types_by_index_definition_name
202206
@indexed_document_types_by_index_definition_name ||=

‎elasticgraph-graphql/lib/elastic_graph/graphql/schema/type.rb‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
require "elastic_graph/errors"
1111
require "elastic_graph/graphql/schema/field"
1212
require "elastic_graph/graphql/schema/enum_value"
13+
require "elastic_graph/support/thread_safe_cache"
1314
require "forwardable"
1415

1516
module ElasticGraph
@@ -36,9 +37,7 @@ def initialize(
3637
)
3738
@schema = schema
3839
@graphql_type = graphql_type
39-
@enum_values_by_name = Hash.new do |hash, key|
40-
hash[key] = lookup_enum_value_by_name(key)
41-
end
40+
@enum_values_by_name = Support::ThreadSafeCache.new # : Support::ThreadSafeCache[::String, EnumValue?]
4241

4342
@index_definitions = index_definitions
4443
@object_runtime_metadata = object_runtime_metadata
@@ -167,7 +166,7 @@ def fields_by_name_in_index
167166
end
168167

169168
def enum_value_named(enum_value_name)
170-
@enum_values_by_name[enum_value_name]
169+
@enum_values_by_name.fetch_or_store(enum_value_name) { lookup_enum_value_by_name(enum_value_name) }
171170
end
172171

173172
def coerce_result(result)

‎elasticgraph-json_ingestion/lib/elastic_graph/json_ingestion/envelope_validator.rb‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
require "elastic_graph/indexer/event_id"
1212
require "elastic_graph/indexer/malformed_event_error"
1313
require "elastic_graph/support/json_schema/validator_factory"
14+
require "elastic_graph/support/thread_safe_cache"
1415

1516
module ElasticGraph
1617
module JSONIngestion
@@ -25,10 +26,7 @@ def initialize(schema_artifacts:, logger:, configure_record_validator: nil)
2526
@schema_artifacts = schema_artifacts
2627
@logger = logger
2728
@configure_record_validator = configure_record_validator
28-
# A `Hash.new { |h, k| h[k] = ... }` cache is not thread-safe on JRuby: concurrent writes can lose
29-
# entries. Guard the cache with a mutex so this validator can be shared across threads on any Ruby.
30-
@validator_factories_by_version = {} # : ::Hash[::Integer, Support::JSONSchema::ValidatorFactory]
31-
@validator_factories_mutex = ::Mutex.new
29+
@validator_factories_by_version = Support::ThreadSafeCache.new # : Support::ThreadSafeCache[::Integer, Support::JSONSchema::ValidatorFactory]
3230
end
3331

3432
# Validates the envelope of each decoded JSON event and builds an {ElasticGraph::Indexer::Event}
@@ -136,9 +134,7 @@ def malformed(decoded_event, validation_target:, message:)
136134
end
137135

138136
def validator_factory_for(json_schema_version)
139-
@validator_factories_mutex.synchronize do
140-
@validator_factories_by_version[json_schema_version] ||= build_validator_factory(json_schema_version)
141-
end
137+
@validator_factories_by_version.fetch_or_store(json_schema_version) { build_validator_factory(json_schema_version) }
142138
end
143139

144140
def build_validator_factory(json_schema_version)

‎elasticgraph-json_ingestion/lib/elastic_graph/json_ingestion/record_preparer_factory.rb‎

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
require "elastic_graph/constants"
1010
require "elastic_graph/indexer/record_preparer"
11+
require "elastic_graph/support/thread_safe_cache"
1112

1213
module ElasticGraph
1314
module JSONIngestion
@@ -18,26 +19,24 @@ class RecordPreparerFactory
1819
def initialize(schema_artifacts)
1920
@schema_artifacts = schema_artifacts
2021

21-
scalar_types_by_name = schema_artifacts.runtime_metadata.scalar_types_by_name
22-
indexing_preparer_by_scalar_type_name = ::Hash.new do |hash, type_name|
23-
hash[type_name] = scalar_types_by_name[type_name]&.load_indexing_preparer&.extension_class
22+
@indexing_preparer_by_scalar_type_name = schema_artifacts.runtime_metadata.scalar_types_by_name.transform_values do |scalar_type|
23+
scalar_type.load_indexing_preparer.extension_class
2424
end # : ::Hash[::String, SchemaArtifacts::RuntimeMetadata::extensionClass?]
2525

26-
@preparers_by_json_schema_version = ::Hash.new do |hash, raw_version|
27-
version = raw_version # : Integer
28-
hash[version] = ElasticGraph::Indexer::RecordPreparer.new(
29-
indexing_preparer_by_scalar_type_name,
30-
build_type_metas_from(@schema_artifacts.json_schemas_for(version))
31-
)
32-
end
26+
@preparers_by_json_schema_version = Support::ThreadSafeCache.new # : Support::ThreadSafeCache[::Integer, ElasticGraph::Indexer::RecordPreparer]
3327
end
3428

3529
# Gets the `ElasticGraph::Indexer::RecordPreparer` for the given JSON schema version.
3630
#
3731
# @param json_schema_version [Integer] the JSON schema version
3832
# @return [ElasticGraph::Indexer::RecordPreparer] the record preparer for the given version
3933
def for_json_schema_version(json_schema_version)
40-
@preparers_by_json_schema_version[json_schema_version] # : ElasticGraph::Indexer::RecordPreparer
34+
@preparers_by_json_schema_version.fetch_or_store(json_schema_version) do
35+
ElasticGraph::Indexer::RecordPreparer.new(
36+
@indexing_preparer_by_scalar_type_name,
37+
build_type_metas_from(@schema_artifacts.json_schemas_for(json_schema_version))
38+
)
39+
end
4140
end
4241

4342
# Gets the `ElasticGraph::Indexer::RecordPreparer` for the latest JSON schema version. Intended primarily

‎elasticgraph-json_ingestion/sig/elastic_graph/json_ingestion/envelope_validator.rbs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,7 @@ module ElasticGraph
2424
def envelope_failure_for: (decodedEvent) -> ::ElasticGraph::Indexer::MalformedEventError[decodedEvent]?
2525
def malformed: (decodedEvent, validation_target: ::String, message: ::String) -> ::ElasticGraph::Indexer::MalformedEventError[decodedEvent]
2626

27-
@validator_factories_by_version: ::Hash[::Integer, Support::JSONSchema::ValidatorFactory]
28-
@validator_factories_mutex: ::Thread::Mutex
27+
@validator_factories_by_version: Support::ThreadSafeCache[::Integer, Support::JSONSchema::ValidatorFactory]
2928
def validator_factory_for: (::Integer) -> Support::JSONSchema::ValidatorFactory
3029
def build_validator_factory: (::Integer) -> Support::JSONSchema::ValidatorFactory
3130

‎elasticgraph-json_ingestion/sig/elastic_graph/json_ingestion/record_preparer_factory.rbs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ module ElasticGraph
99
private
1010

1111
@schema_artifacts: schemaArtifacts
12-
@preparers_by_json_schema_version: ::Hash[::Integer, ::ElasticGraph::Indexer::RecordPreparer]
12+
@indexing_preparer_by_scalar_type_name: ::Hash[::String, SchemaArtifacts::RuntimeMetadata::extensionClass?]
13+
@preparers_by_json_schema_version: Support::ThreadSafeCache[::Integer, ::ElasticGraph::Indexer::RecordPreparer]
1314

1415
def build_type_metas_from: (::Hash[::String, untyped]) -> ::Array[::ElasticGraph::Indexer::RecordPreparer::TypeMetadata]
1516
end

‎elasticgraph-schema_artifacts/lib/elastic_graph/schema_artifacts/from_disk.rb‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
require "elastic_graph/schema_artifacts/artifacts_helper_methods"
1212
require "elastic_graph/schema_artifacts/runtime_metadata/schema"
1313
require "elastic_graph/support/memoizable_data"
14+
require "elastic_graph/support/thread_safe_cache"
1415
require "yaml"
1516

1617
module ElasticGraph
@@ -69,7 +70,7 @@ def json_schemas_for(version)
6970
"Available versions: #{available_json_schema_versions.sort.join(", ")}."
7071
end
7172

72-
json_schemas_by_version[version] # : ::Hash[::String, untyped]
73+
@json_schemas_by_version.fetch_or_store(version) { load_json_schema(version) }
7374
end
7475

7576
# Provides the set of available JSON schema versions.
@@ -134,6 +135,10 @@ def runtime_metadata
134135

135136
private
136137

138+
def after_initialize
139+
@json_schemas_by_version = Support::ThreadSafeCache.new # : Support::ThreadSafeCache[::Integer, ::Hash[::String, untyped]]
140+
end
141+
137142
def read_artifact(artifact_name)
138143
file_name = ::File.join(artifacts_dir, artifact_name)
139144

@@ -149,13 +154,6 @@ def parsed_yaml_from(artifact_name)
149154
::YAML.safe_load(read_artifact(artifact_name))
150155
end
151156

152-
def json_schemas_by_version
153-
@json_schemas_by_version ||= ::Hash.new do |hash, raw_json_schema_version|
154-
json_schema_version = raw_json_schema_version # : Integer
155-
hash[json_schema_version] = load_json_schema(json_schema_version)
156-
end
157-
end
158-
159157
# Loads the given JSON schema version from disk.
160158
def load_json_schema(json_schema_version)
161159
parsed_yaml_from(::File.join(JSON_SCHEMAS_BY_VERSION_DIRECTORY, "v#{json_schema_version}.yaml"))

0 commit comments

Comments
 (0)