featurevisor 4.0.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md CHANGED
@@ -1,49 +1,56 @@
1
1
  # Featurevisor Ruby SDK <!-- omit in toc -->
2
2
 
3
- Use the Featurevisor Ruby SDK to evaluate flags, variations and variables in Ruby applications.
3
+ The Featurevisor Ruby SDK evaluates flags, variations and variables in Ruby applications, from a datafile it holds in memory.
4
4
 
5
5
  ## Table of contents <!-- omit in toc -->
6
6
 
7
- - [Installation](#installation)
8
- - [Initialization](#initialization)
9
- - [Public API](#public-api)
10
- - [Evaluation types](#evaluation-types)
7
+ - [Install](#install)
8
+ - [Create an instance](#create-an-instance)
9
+ - [Concurrency](#concurrency)
11
10
  - [Context](#context)
12
- - [Setting initial context](#setting-initial-context)
13
- - [Setting after initialization](#setting-after-initialization)
14
- - [Replacing existing context](#replacing-existing-context)
15
- - [Manually passing context](#manually-passing-context)
16
- - [Check if enabled](#check-if-enabled)
17
- - [Getting variation](#getting-variation)
18
- - [Getting variables](#getting-variables)
19
- - [Getting feature variables](#getting-feature-variables)
20
- - [Type specific methods](#type-specific-methods)
21
- - [Getting global variables](#getting-global-variables)
22
- - [Conditions](#conditions)
23
- - [Composition](#composition)
24
- - [Getting evaluations](#getting-evaluations)
25
- - [Sticky](#sticky)
26
- - [Initialize with sticky](#initialize-with-sticky)
27
- - [Set sticky afterwards](#set-sticky-afterwards)
28
- - [Setting datafile](#setting-datafile)
29
- - [Merging by default](#merging-by-default)
30
- - [Replacing](#replacing)
31
- - [Loading datafiles on demand](#loading-datafiles-on-demand)
32
- - [Updating datafile](#updating-datafile)
33
- - [Interval-based update](#interval-based-update)
34
- - [Diagnostics](#diagnostics)
35
- - [Levels](#levels)
36
- - [Handler](#handler)
11
+ - [Check a flag](#check-a-flag)
12
+ - [Get a variation](#get-a-variation)
13
+ - [Get a variable](#get-a-variable)
14
+ - [Typed methods](#typed-methods)
15
+ - [Composed variables](#composed-variables)
16
+ - [Default values](#default-values)
17
+ - [Evaluate everything at once](#evaluate-everything-at-once)
18
+ - [Hand results from server to client](#hand-results-from-server-to-client)
19
+ - [Sticky values](#sticky-values)
20
+ - [Update the datafile](#update-the-datafile)
21
+ - [Merge or replace](#merge-or-replace)
22
+ - [Refresh on an interval](#refresh-on-an-interval)
23
+ - [Child instances](#child-instances)
37
24
  - [Events](#events)
38
25
  - [`datafile_set`](#datafile_set)
39
26
  - [`context_set`](#context_set)
40
- - [`sticky_features_set` and `sticky_variables_set`](#sticky_features_set-and-sticky_variables_set)
27
+ - [`sticky_features_set`](#sticky_features_set)
28
+ - [`sticky_variables_set`](#sticky_variables_set)
41
29
  - [`error`](#error)
30
+ - [Diagnostics](#diagnostics)
31
+ - [Evaluation errors](#evaluation-errors)
42
32
  - [Evaluation details](#evaluation-details)
33
+ - [Evaluation reasons](#evaluation-reasons)
43
34
  - [Modules](#modules)
44
- - [Defining a module](#defining-a-module)
45
- - [Registering modules](#registering-modules)
46
- - [Child instance](#child-instance)
35
+ - [Dependency evaluations](#dependency-evaluations)
36
+ - [Register a module](#register-a-module)
37
+ - [Read the datafile from a module](#read-the-datafile-from-a-module)
38
+ - [Schemas](#schemas)
39
+ - [Create a schemas instance](#create-a-schemas-instance)
40
+ - [Validate a value](#validate-a-value)
41
+ - [Read the issues](#read-the-issues)
42
+ - [Get a handle](#get-a-handle)
43
+ - [Read constraints and choices](#read-constraints-and-choices)
44
+ - [Read annotations](#read-annotations)
45
+ - [Follow the values typed so far](#follow-the-values-typed-so-far)
46
+ - [Choose the messages](#choose-the-messages)
47
+ - [Check in code](#check-in-code)
48
+ - [Options from your application](#options-from-your-application)
49
+ - [Validate on the server](#validate-on-the-server)
50
+ - [Listen for changes](#listen-for-changes)
51
+ - [Patterns](#patterns)
52
+ - [Failing closed](#failing-closed)
53
+ - [Fields validated alone](#fields-validated-alone)
47
54
  - [Close](#close)
48
55
  - [OpenFeature](#openfeature)
49
56
  - [CLI usage](#cli-usage)
@@ -60,825 +67,880 @@ Use the Featurevisor Ruby SDK to evaluate flags, variations and variables in Rub
60
67
 
61
68
  <!-- FEATUREVISOR_DOCS_BEGIN -->
62
69
 
63
- ## Installation
64
-
65
- Upgrading an existing application? Follow the [Ruby migration guide](https://featurevisor.com/docs/migrations/v4/ruby/).
70
+ ## Install
66
71
 
67
- Add this line to your application's Gemfile:
72
+ Add the gem to your application's Gemfile:
68
73
 
69
74
  ```ruby
70
75
  gem 'featurevisor', '~> 4.0'
71
76
  ```
72
77
 
73
- And then execute:
74
-
75
- ```bash
76
- bundle install
77
- ```
78
-
79
- Or install it yourself as:
80
-
81
- ```bash
82
- gem install featurevisor -v "~> 4.0"
83
- ```
78
+ Then run `bundle install`, or install it yourself with `gem install featurevisor -v "~> 4.0"`. Upgrading an existing application? Follow the [Ruby migration guide](https://featurevisor.com/docs/migrations/v4/ruby/).
84
79
 
85
- ## Initialization
80
+ ## Create an instance
86
81
 
87
- The SDK can be initialized by passing [datafile](https://featurevisor.com/docs/building-datafiles/) content directly:
82
+ Fetch a [datafile](https://featurevisor.com/docs/building-datafiles/) and create an instance with it:
88
83
 
89
84
  ```ruby
90
85
  require 'featurevisor'
91
86
  require 'net/http'
92
87
  require 'json'
93
88
 
94
- # Fetch datafile from URL
95
- datafile_url = 'https://cdn.yoursite.com/featurevisor-all.json'
89
+ datafile_url = 'https://cdn.example.com/featurevisor-all.json'
96
90
  response = Net::HTTP.get_response(URI(datafile_url))
97
91
  unless response.is_a?(Net::HTTPSuccess)
98
92
  raise "Datafile request failed: HTTP #{response.code}"
99
93
  end
100
94
 
101
- # Parse JSON with symbolized keys (required)
102
95
  datafile_content = JSON.parse(response.body, symbolize_names: true)
103
96
 
104
- # Create SDK instance
105
97
  f = Featurevisor.create_featurevisor(
106
98
  datafile: datafile_content
107
99
  )
108
100
  begin
109
- puts f.is_enabled('checkout', { userId: '123' })
101
+ puts f.is_enabled('checkout', { userId: 'user-4' })
110
102
  ensure
111
103
  f.close
112
104
  end
113
105
  ```
114
106
 
115
- Network errors, unsuccessful HTTP responses and invalid JSON stop initialization. Handle these exceptions at your application's startup boundary.
107
+ This example closes the instance at once. In a long running application, keep it for every evaluation and close it at shutdown. Parse a datafile with `symbolize_names: true`, which the SDK needs, or pass the JSON string and let the SDK parse it. Every option is optional, so an instance can start without a datafile and [receive one later](#update-the-datafile):
116
108
 
117
- **Important**: When parsing JSON datafiles, you must use `symbolize_names: true` to ensure proper key handling by the SDK.
109
+ | Option | Sets |
110
+ | ------------------------------------- | -------------------------------- |
111
+ | `datafile` | The datafile to evaluate |
112
+ | `context` | The [instance context](#context) |
113
+ | `sticky_features`, `sticky_variables` | [Sticky values](#sticky-values) |
114
+ | `log_level`, `on_diagnostic` | [Diagnostics](#diagnostics) |
115
+ | `modules` | [Modules](#modules) |
118
116
 
119
- Pass a JSON string for the SDK to parse:
117
+ Create one instance and reuse it. On a server that handles many users, give each request a [child instance](#child-instances).
120
118
 
121
- ```ruby
122
- # Option 1: Parse JSON yourself (recommended)
123
- datafile_content = JSON.parse(json_string, symbolize_names: true)
124
- f = Featurevisor.create_featurevisor(datafile: datafile_content)
119
+ ### Concurrency
125
120
 
126
- # Option 2: Pass JSON string directly (automatic parsing)
127
- f = Featurevisor.create_featurevisor(datafile: json_string)
128
- ```
121
+ On MRI, evaluations are safe from many threads, with one thread refreshing the datafile, since warm reads rely on MRI's execution model. Other Ruby implementations are not guaranteed. Apply changes, such as `set_datafile`, `set_context`, `set_sticky_features`, `set_sticky_variables`, `add_module`, `remove_module` and `close`, from one thread at a time, never during evaluations. Module, event and diagnostic callbacks synchronize any state of their own.
129
122
 
130
- ### Public API
123
+ ## Context
124
+
125
+ Context is a plain hash of [attribute](https://featurevisor.com/docs/attributes/) values, with symbol keys. The instance keeps a context of its own, and each evaluation can add to it.
131
126
 
132
- The main runtime API is `Featurevisor.create_featurevisor`:
127
+ Set it when creating the instance:
133
128
 
134
129
  ```ruby
135
130
  f = Featurevisor.create_featurevisor(
136
- datafile: datafile_content
131
+ datafile: datafile_content,
132
+ context: {
133
+ country: 'nl'
134
+ }
137
135
  )
138
136
  ```
139
137
 
140
- Most applications only need this factory and the returned `Featurevisor::Instance`. Public extension and observability APIs include modules, diagnostics, events, and the datafile structures accepted by the factory.
138
+ Add to it later with `set_context`, or replace it by passing `true` as the second argument:
141
139
 
142
- Concurrent evaluations and a single background datafile refresh writer are supported on MRI. Warm entity reads rely on MRI's execution model. Thread safety is not guaranteed on other Ruby implementations. CI covers MRI 3.0 and 3.4. Serialize writer operations. Do not change context, sticky state or modules, or close the instance, concurrently with evaluations on other threads. Module, event, and diagnostic callbacks must synchronize mutable state that they capture.
143
-
144
- ### Evaluation types
140
+ ```ruby
141
+ f.set_context({
142
+ userId: 'user-4'
143
+ })
145
144
 
146
- Featurevisor evaluates four kinds of values:
145
+ f.set_context({
146
+ userId: 'user-2',
147
+ country: 'nl'
148
+ }, true)
149
+ ```
147
150
 
148
- - [**Flag**](#check-if-enabled) (`true` or `false`): whether the feature is enabled or not
149
- - [**Variation**](#getting-variation) (`String`): the variation of the feature (if any)
150
- - [**Feature variable**](#getting-feature-variables): a configuration value owned by a feature
151
- - [**Global variable**](#getting-global-variables): a configuration value evaluated independently of a feature
151
+ Context passed to an evaluation is merged over the instance context for that call only:
152
152
 
153
- These evaluations are run against the provided context.
153
+ ```ruby
154
+ context = {
155
+ userId: 'user-4',
156
+ country: 'nl'
157
+ }
154
158
 
155
- ## Context
159
+ f.is_enabled('checkout', context)
160
+ ```
156
161
 
157
- Contexts are [attribute](https://featurevisor.com/docs/attributes/) values you pass to the SDK for evaluating [features](https://featurevisor.com/docs/features/) against.
162
+ `get_context` returns the instance context, and `get_context({ country: 'de' })` shows it merged with extra values without storing them.
158
163
 
159
- Conditions compare these attributes using the [operators](https://featurevisor.com/docs/operators/), including `empty` and `notEmpty`.
164
+ Dates compare as portable timestamp strings, `Time` or `DateTime`, by their instant, truncated to milliseconds. Offsets stay within 14 hours and years within 1 and 9999. A plain `Date` has no time or offset, so pass `Time.utc(2026, 1, 1)` or `'2026-01-01T00:00:00Z'` instead.
160
165
 
161
- Date comparisons with `before` and `after` accept portable timestamp strings, `Time` and `DateTime`. Native values are compared by their instant and truncated to milliseconds without rounding. Both the native written year and the UTC year must be within 1 to 9999. Native offsets must have a magnitude of at most 14 hours, including any seconds or fractions supported by the type. Offsets within that limit retain their full precision. A plain `Date` is not accepted because it has no time or offset. Pass `Time.utc(2026, 1, 1)` or `'2026-01-01T00:00:00Z'` instead of `Date.new(2026, 1, 1)`. Invalid values make both operators return `false`.
166
+ ## Check a flag
162
167
 
163
- They are plain hashes:
168
+ `is_enabled` reads a [flag](https://featurevisor.com/docs/flags/). Dutch users have the new `checkout`:
164
169
 
165
170
  ```ruby
166
171
  context = {
167
- userId: '123',
168
- country: 'nl',
169
- # ...other attributes
172
+ userId: 'user-4',
173
+ country: 'nl'
170
174
  }
175
+
176
+ if f.is_enabled('checkout', context)
177
+ # show the new checkout
178
+ end
171
179
  ```
172
180
 
173
- ### Setting initial context
181
+ ## Get a variation
174
182
 
175
- Set context when you create the instance:
183
+ `get_variation` returns the [variation](https://featurevisor.com/docs/variations/) of a feature, or `nil` if the feature is disabled or has none:
176
184
 
177
185
  ```ruby
178
- require 'featurevisor'
186
+ variation = f.get_variation('pricing', context)
179
187
 
180
- f = Featurevisor.create_featurevisor(
181
- context: {
182
- deviceId: '123',
183
- country: 'nl'
184
- }
185
- )
188
+ if variation == 'treatment'
189
+ # show the new pricing
190
+ end
186
191
  ```
187
192
 
188
- This is useful for values that don't change too frequently and available at the time of application startup.
193
+ For `user-4` it returns `'control'`, and for `user-2` it returns `'treatment'`.
189
194
 
190
- ### Setting after initialization
195
+ ## Get a variable
191
196
 
192
- Add context later:
197
+ `get_variable` reads a [feature variable](https://featurevisor.com/docs/variables/#feature-variables) with a feature key and a variable key. For `user-4`, the `netherlands` rule sets the buy button's label to `'Nu kopen'`:
193
198
 
194
199
  ```ruby
195
- f.set_context({
196
- userId: '234'
197
- })
200
+ label = f.get_variable('buyButton', 'label', context)
198
201
  ```
199
202
 
200
- This will merge the new context with the existing one (if already set).
201
-
202
- ### Replacing existing context
203
-
204
- Replace the context by passing `true` as the second argument:
203
+ With a context as its second argument, it reads a [global variable](https://featurevisor.com/docs/variables/#global-variables) instead. `supportEmail` returns `'support-nl@example.com'` for `user-4`:
205
204
 
206
205
  ```ruby
207
- f.set_context({
208
- deviceId: '123',
209
- userId: '234',
210
- country: 'nl',
211
- browser: 'chrome'
212
- }, true) # replace existing context
206
+ email = f.get_variable('supportEmail', context)
213
207
  ```
214
208
 
215
- ### Manually passing context
209
+ A string second argument means a feature variable, and a hash means context for a global variable. The typed methods below follow the same rule.
216
210
 
217
- Pass context to one evaluation without changing the instance context:
211
+ Treat returned hashes and arrays as read only. The SDK can share them with its datafile rather than copy them on every evaluation, so copy a value before changing it, and never change a datafile after passing it to the instance.
218
212
 
219
- ```ruby
220
- context = {
221
- userId: '123',
222
- country: 'nl'
223
- }
213
+ ### Typed methods
224
214
 
225
- is_enabled = f.is_enabled('checkout', context)
226
- variation = f.get_variation('checkout', context)
227
- variable_value = f.get_variable('checkout', 'bgColor', context)
215
+ Each typed method returns `nil` when the value has a different type, and never converts it. `get_variable_integer` returns `nil` for the string `'1'`, and `get_variable_boolean` returns `nil` for `'true'`.
216
+
217
+ `get_variable_number` reads a variable of [type `number`](https://featurevisor.com/docs/variables/#number) as a `Float`, and also `double` in datafiles built before v4.
218
+
219
+ | Method | Returns |
220
+ | ---------------------- | ---------------------------- |
221
+ | `get_variable_boolean` | `true` or `false` |
222
+ | `get_variable_string` | `String` |
223
+ | `get_variable_integer` | `Integer` |
224
+ | `get_variable_number` | `Float`, whole or fractional |
225
+ | `get_variable_array` | `Array` |
226
+ | `get_variable_object` | `Hash` |
227
+ | `get_variable_json` | Any JSON value |
228
+
229
+ ```ruby
230
+ settings = f.get_variable_object('checkoutSettings', context)
231
+ # { currency: 'EUR', paymentMethods: ['card'] }
228
232
  ```
229
233
 
230
- When manually passing context, it will merge with existing context set to the SDK instance before evaluating the specific value.
234
+ ### Composed variables
231
235
 
232
- ## Check if enabled
236
+ Read a [composed global variable](https://featurevisor.com/docs/variables/#compose-values) like any other global variable. For a string `compose` alias, choose the getter for the source's type, such as `get_variable_string` for an alias of `supportEmail`. It returns what the source's own getter returns, including decoded JSON and `nil`, with no wrapper or copy.
233
237
 
234
- Check whether a feature is enabled:
238
+ A composition is evaluated in this order:
235
239
 
236
- ```ruby
237
- feature_key = 'checkout'
240
+ 1. A sticky value for the whole variable, which skips everything after it.
241
+ 2. Root `conditions`. When they miss, no source is read and no override runs. The result is `disabledValue` when supplied, otherwise `nil`, with reason `conditions_unmet`.
242
+ 3. The sources, with their own sticky values, the context and modules taking part as usual.
243
+ 4. The [overrides](https://featurevisor.com/docs/variables/#override-composed-values), which run as they do for any global variable.
238
244
 
239
- is_enabled = f.is_enabled(feature_key)
245
+ Compositions have no `defaultValue` or `useDefaultWhenDisabled`. With no override match, the reason is `variable_composed`, and a match reports `variable_override_rule`, with `variable_override_paths` listing every override that changed the value. Only the outer hash of a composition is fresh, so treat what it holds as read only.
240
246
 
241
- if is_enabled
242
- # do something
243
- end
244
- ```
247
+ ## Default values
245
248
 
246
- Pass additional context to one evaluation:
249
+ Pass `default_variation_value` or `default_variable_value` in the options for when an evaluation produces no value, such as a feature missing from the datafile:
247
250
 
248
251
  ```ruby
249
- is_enabled = f.is_enabled(feature_key, {
250
- # ...additional context
251
- })
252
+ label = f.get_variable(
253
+ 'buyButton',
254
+ 'label',
255
+ context,
256
+ { default_variable_value: 'Buy' }
257
+ )
252
258
  ```
253
259
 
254
- ## Getting variation
260
+ A default counts as given whenever the key is present, so `''`, `0`, `false` and `nil` are all valid defaults.
255
261
 
256
- Evaluate a feature's [variations](https://featurevisor.com/docs/features/#variations):
262
+ ## Evaluate everything at once
257
263
 
258
- ```ruby
259
- feature_key = 'checkout'
260
-
261
- variation = f.get_variation(feature_key)
264
+ `get_feature_evaluations` evaluates every loaded feature, or only the keys you pass:
262
265
 
263
- if variation == 'treatment'
264
- # do something for treatment variation
265
- else
266
- # handle default/control variation
267
- end
266
+ ```ruby
267
+ f.get_feature_evaluations(context, %w[checkout pricing buyButton])
268
+ # {
269
+ # checkout: { enabled: true },
270
+ # pricing: { enabled: true, variation: 'control' },
271
+ # buyButton: {
272
+ # enabled: true,
273
+ # variation: 'treatment',
274
+ # variables: { label: 'Nu kopen', colour: '#2563eb' }
275
+ # }
276
+ # }
268
277
  ```
269
278
 
270
- Pass additional context to one evaluation:
279
+ `get_variable_evaluations` does the same for global variables:
271
280
 
272
281
  ```ruby
273
- variation = f.get_variation(feature_key, {
274
- # ...additional context
275
- })
282
+ f.get_variable_evaluations(context, %w[supportEmail checkoutSettings])
276
283
  ```
277
284
 
278
- ## Getting variables
285
+ To see what is loaded without evaluating anything:
279
286
 
280
- ### Getting feature variables
287
+ - `get_feature_keys` lists every feature in the datafile, enabled or not.
288
+ - `get_variable_keys` lists global variables, and `get_variable_keys('buyButton')` lists that feature's variables.
289
+ - `has_variations?('pricing')` is `true` when a feature has variations, and `false` for an unknown feature.
281
290
 
282
- Evaluate a feature's [variables](https://featurevisor.com/docs/features/#variables):
291
+ ### Hand results from server to client
283
292
 
284
- ```ruby
285
- variable_key = 'bgColor'
293
+ Both results have the shape [sticky values](#sticky-values) take. A server can evaluate once per request and pass the results to the browser, so the first render matches what the server saw. The JavaScript SDK's [sticky values](https://featurevisor.com/docs/sdks/javascript/#hand-results-from-server-to-client) read them there.
294
+
295
+ ## Sticky values
296
+
297
+ Sticky values take precedence over the datafile. Use them to keep a user's result fixed, to answer before a datafile has loaded, or in unit tests:
286
298
 
287
- bg_color_value = f.get_variable('checkout', variable_key)
299
+ ```ruby
300
+ f = Featurevisor.create_featurevisor(
301
+ sticky_features: {
302
+ checkout: { enabled: true },
303
+ pricing: {
304
+ enabled: true,
305
+ variation: 'treatment'
306
+ }
307
+ },
308
+ sticky_variables: {
309
+ supportEmail: 'support@example.com'
310
+ }
311
+ )
288
312
  ```
289
313
 
290
- Pass additional context to one evaluation:
314
+ A sticky feature can also set `variables`. Change sticky values later with `set_sticky_features` and `set_sticky_variables`. Both merge by default, and replace the whole map when the second argument is `true`:
291
315
 
292
316
  ```ruby
293
- bg_color_value = f.get_variable('checkout', variable_key, {
294
- # ...additional context
295
- })
317
+ f.set_sticky_features({
318
+ checkout: { enabled: false }
319
+ }, true)
296
320
  ```
297
321
 
298
- ### Type specific methods
322
+ Treat sticky maps as read only once given to an instance, and change them only through these methods.
299
323
 
300
- Next to generic `get_variable()` methods, there are also type specific methods available for convenience:
324
+ ## Update the datafile
325
+
326
+ `set_datafile` gives the instance a newer datafile, parsed with symbol keys or as a JSON string:
301
327
 
302
328
  ```ruby
303
- f.get_variable_boolean(feature_key, variable_key, context = {})
304
- f.get_variable_string(feature_key, variable_key, context = {})
305
- f.get_variable_integer(feature_key, variable_key, context = {})
306
- f.get_variable_number(feature_key, variable_key, context = {})
307
- f.get_variable_array(feature_key, variable_key, context = {})
308
- f.get_variable_object(feature_key, variable_key, context = {})
309
- f.get_variable_json(feature_key, variable_key, context = {})
329
+ f.set_datafile(datafile_content)
310
330
  ```
311
331
 
312
- Type specific methods do not coerce values. `get_variable_integer` returns `nil` for the string `"1"`, and boolean getters return `nil` for non-boolean values.
332
+ It returns `true` when the datafile is accepted, even if nothing changed, and `false` when it is rejected or the instance is closed. A rejected datafile leaves the previous one in place and is reported through [diagnostics](#diagnostics).
313
333
 
314
- `get_variable_number` reads a variable of type `number` as a `Float`, whether it holds `3` or `4.5`. Datafiles built before v4 call that type `double`, and it reads the same way. The v3 name `get_variable_double` was removed in v4.
334
+ ### Merge or replace
315
335
 
316
- ### Getting global variables
336
+ By default, the new datafile is merged into the current one:
317
337
 
318
- Global variables use the same methods with a single variable key:
338
+ - Its features, segments and global variables replace those with the same keys.
339
+ - Definitions it does not contain are kept.
340
+ - Its `revision` and `schemaVersion` are taken.
341
+
342
+ Pass `true` to replace the current datafile entirely. Do this when refreshing a complete datafile, so definitions removed from it do not linger:
319
343
 
320
344
  ```ruby
321
- message = f.get_variable_string('welcomeMessage', context)
322
- value = f.get_variable('checkoutSettings', context)
323
- evaluation = f.evaluate_variable('checkoutSettings', context)
345
+ f.set_datafile(datafile_content, true)
324
346
  ```
325
347
 
326
- Overrides and conditions are applied for you. See [Variables](https://featurevisor.com/docs/variables/#global-variables) and [Conditions](https://featurevisor.com/docs/conditions/) for how to define them.
348
+ Merging is what lets one instance hold datafiles for several [targets](https://featurevisor.com/docs/targets/), loaded as each part of the application needs them. See [Loading datafiles on demand](https://featurevisor.com/docs/use-cases/on-demand-datafiles/).
349
+
350
+ ### Refresh on an interval
327
351
 
328
- To see which overrides changed a value, inspect `variable_override_paths` in the detailed evaluation:
352
+ Fetch the datafile again every few minutes, from one thread:
329
353
 
330
354
  ```ruby
331
- evaluation = f.evaluate_variable('runtimePolicy', country: 'nl')
332
- value = evaluation[:variable_value]
333
- matched_paths = evaluation[:variable_override_paths]
355
+ refresh = Thread.new do
356
+ loop do
357
+ sleep(5 * 60)
358
+ begin
359
+ response = Net::HTTP.get_response(URI(datafile_url))
360
+ next unless response.is_a?(Net::HTTPSuccess)
361
+
362
+ f.set_datafile(JSON.parse(response.body, symbolize_names: true), true)
363
+ rescue StandardError => error
364
+ warn "Could not refresh datafile: #{error.message}"
365
+ end
366
+ end
367
+ end
334
368
  ```
335
369
 
336
- Treat sticky feature and variable maps, including nested values passed to the SDK or returned by modules, as read only during evaluation. Use the SDK setters to change owned sticky state.
370
+ A failed fetch keeps the previous datafile. `set_datafile` does not raise for an invalid datafile, it reports it through diagnostics. Stop the thread with `refresh.kill` when you stop, since `close` does not stop your threads. Each accepted update emits [`datafile_set`](#datafile-set).
337
371
 
338
- Modules should return the same result for the same input during one evaluation. Pass values that change through context.
372
+ ## Child instances
339
373
 
340
- ## Conditions
374
+ A server handles many users at once, so give each request a child with its own context:
341
375
 
342
- [Conditions](https://featurevisor.com/docs/conditions/) are shared by segments, feature and global variable root gates, force entries, traffic rules and variable overrides. Generated v4 datafiles use `schemaVersion: "4"`. Arrays imply AND. Logical expressions use `and`, `or` and `not`. NOT negates the AND of its direct children. Empty expressions are false.
376
+ ```ruby
377
+ child = f.spawn({
378
+ userId: 'user-4',
379
+ country: 'nl'
380
+ })
343
381
 
344
- Leaves compare context attributes, reference a segment by its literal string key, check a feature's enabled state and optional variation, or compare an evaluated variable. Feature enabled checks default to true. Variable leaves may name a feature owner and use already compiled path arrays. Dots and slashes in variable keys remain literal.
382
+ child.is_enabled('checkout')
383
+ ```
345
384
 
346
- For example, a compiled root gate can combine all four leaf kinds:
385
+ - The child copies the parent's context keys when it is spawned, and its own values win. Keys the parent adds later still reach it.
386
+ - Sticky values are not inherited. Pass `{ sticky_features: ... }` as the second argument when the child needs some.
387
+ - A child has the parent's evaluation methods, plus `get_context`, `set_context`, `set_sticky_features`, `set_sticky_variables`, `on` and `close`.
388
+ - `close` removes the child's listeners, including the ones it registered on its parent.
347
389
 
348
- ```json
349
- {
350
- "conditions": [
351
- {"attribute": "country", "operator": "equals", "value": "nl"},
352
- "eligibleAudience",
353
- {"feature": "checkout", "variation": "treatment"},
354
- {"variable": "policy", "path": ["items", 0, "enabled"], "operator": "equals", "value": true}
355
- ]
356
- }
357
- ```
390
+ ## Events
358
391
 
359
- Continue using ordinary getters:
392
+ `on` subscribes to an event with a block and returns a lambda that unsubscribes.
393
+
394
+ ### `datafile_set`
395
+
396
+ Emitted for every accepted datafile:
360
397
 
361
398
  ```ruby
362
- enabled = f.is_enabled('checkout', country: 'nl')
363
- policy = f.get_variable('policy')
399
+ unsubscribe = f.on('datafile_set') do |event|
400
+ revision = event[:revision]
401
+ previous_revision = event[:previousRevision]
402
+ revision_changed = event[:revisionChanged]
403
+ replaced = event[:replaced]
404
+ features = event[:features]
405
+ variables = event[:variables]
406
+ segments = event[:segments]
407
+
408
+ # evaluate the listed features and variables again
409
+ end
410
+
411
+ unsubscribe.call
364
412
  ```
365
413
 
366
- Feature evaluation checks sticky state, force, its root gate and then traffic rules. Force bypasses the gate. Global variables check sticky state and their gate before reading sources or applying overrides. A missed root gate reports `conditions_unmet` and `evaluation[:conditions]`. Variation and feature variable evaluations retain their ordinary disabled reasons and fallbacks.
414
+ `replaced` says whether the datafile replaced the previous one or merged into it. `features` and `variables` list the keys whose results may have changed: those added, updated or removed, and those that depend on them through conditions, segments and composition sources, however indirectly. Evaluate those again and you have everything that changed.
367
415
 
368
- Conditions preserve written order and short circuit. Segments and getter dependencies share the current request session and a combined depth limit of 256 internal handoffs. Cycles and excessive depth fail the whole evaluation. Later independent calls start fresh sessions. An ordinary completed false or nil getter result remains a value.
416
+ `segments` lists the segments whose definitions were added, changed or, on a replace, removed. If a new datafile has the `netherlands` segment take Belgium too, `segments` is `[:netherlands]`, and `features` and `variables` include `checkout` and `supportEmail`, whose conditions read it. The first datafile lists every feature, global variable and segment. `sections` lists the changed entries of each [datafile section](#read-the-datafile-from-a-module), such as `schemas`.
369
417
 
370
- ## Composition
418
+ ### `context_set`
371
419
 
372
- [Composed variables](https://featurevisor.com/docs/variables/#compose-values) read sources through ordinary getters with the effective context, modules and sticky state. A compiled list assembles one fresh outer hash with literal property names:
420
+ Emitted by `set_context`:
373
421
 
374
- ```json
375
- {
376
- "type": "object",
377
- "compose": [
378
- {"key": "enabled", "feature": "checkout"},
379
- {"key": "assignment", "feature": "checkout", "variation": true},
380
- {"key": "title", "feature": "checkout", "variable": "title"},
381
- {"key": "policy", "variable": "policy"}
382
- ]
383
- }
422
+ ```ruby
423
+ f.on('context_set') do |event|
424
+ context = event[:context] # the new instance context
425
+ keys = event[:keys] # the top level keys whose values changed
426
+ end
384
427
  ```
385
428
 
386
- The string form, `"compose": "policy"`, is an alias of that literal global variable key. It returns the evaluated source directly, including false, zero, empty strings, arrays and nil. JSON sources are decoded exactly once, including when their decoded strings resemble JSON.
429
+ `keys` compares values, so a key set again to the value it already holds is not listed. Starting from the instance context `{ userId: 'user-4', country: 'nl' }`:
387
430
 
388
431
  ```ruby
389
- screen = f.get_variable('screen', country: 'nl')
390
- details = f.evaluate_variable('screen', country: 'nl')
391
- ```
432
+ f.set_context(
433
+ country: 'de'
434
+ )
435
+ # keys: [:country]
392
436
 
393
- Compositions do not declare `defaultValue` or `useDefaultWhenDisabled`. They may have root `conditions` and `disabledValue`. An unmet gate skips every source and override and returns the disabled value or nil. Whole variable sticky state bypasses both assembly and overrides. Explicit defaults supplied to the outer getter are never forwarded to sources.
437
+ f.set_context(
438
+ country: 'de',
439
+ plan: 'paid'
440
+ )
441
+ # keys: [:plan]
394
442
 
395
- All members are read before runtime overrides. Overrides use the existing mutation operations and provenance fields. The reason is `variable_composed`, or `variable_override_rule` when an override matches. Mutations copy changed containers without modifying source values, sibling properties or sticky values.
443
+ f.set_context(
444
+ {
445
+ userId: 'user-4',
446
+ country: 'de'
447
+ },
448
+ true
449
+ )
450
+ # keys: [:plan]
451
+ ```
396
452
 
397
- Treat returned hashes and arrays as read only. Composition properties and aliases keep ordinary getter ownership, so descendants may be shared. Only the map composition's outer hash is guaranteed to be fresh. Ordinary source getter failures retain their normal fallbacks. Dependency failures invalidate the whole composition.
453
+ A replace also lists the keys it removed, as `plan` above. Hashes and arrays compare item by item, and numbers by value, so `30` and `30.0` are the same, but a hash or array given again as the same object counts as changed, since it may have been changed in place.
398
454
 
399
- ## Getting evaluations
455
+ ### `sticky_features_set`
400
456
 
401
- Evaluate all features available in the instance:
457
+ Emitted by `set_sticky_features`, with `features`, every feature that had a sticky value before the call or has one after it, and `replaced`:
402
458
 
403
459
  ```ruby
404
- all_evaluations = f.get_feature_evaluations({})
405
-
406
- puts all_evaluations
407
- # {
408
- # checkout: {
409
- # enabled: true,
410
- # variation: "control",
411
- # variables: {
412
- # myVariableKey: "myVariableValue",
413
- # },
414
- # },
415
- #
416
- # anotherFeature: {
417
- # enabled: true,
418
- # variation: "treatment",
419
- # }
420
- # }
460
+ f.on('sticky_features_set') { |event| puts event[:features] }
421
461
  ```
422
462
 
423
- This is handy especially when you want to pass all evaluations from a backend application to the frontend.
463
+ ### `sticky_variables_set`
424
464
 
425
- Global variable values are available separately:
465
+ Emitted by `set_sticky_variables`, with `variables` and `replaced`:
426
466
 
427
467
  ```ruby
428
- global_variables = f.get_variable_evaluations({})
468
+ f.on('sticky_variables_set') { |event| puts event[:variables] }
429
469
  ```
430
470
 
431
- ## Sticky
432
-
433
- Set sticky values to take precedence over feature evaluation against the [datafile](https://featurevisor.com/docs/building-datafiles/):
434
-
435
- Sticky values belong to an SDK or child instance. Feature and global variable sticky values are independent.
471
+ ### `error`
436
472
 
437
- ### Initialize with sticky
473
+ Emitted for every diagnostic at `error`:
438
474
 
439
475
  ```ruby
440
- require 'featurevisor'
441
-
442
- f = Featurevisor.create_featurevisor(
443
- sticky_features: {
444
- checkout: {
445
- enabled: true,
446
- # optional
447
- variation: 'treatment',
448
- variables: {
449
- myVariableKey: 'myVariableValue'
450
- }
451
- },
452
- anotherFeatureKey: {
453
- enabled: false
454
- }
455
- },
456
- sticky_variables: {
457
- welcomeMessage: 'Welcome back'
458
- }
459
- )
476
+ f.on('error') { |event| warn event[:diagnostic][:message] }
460
477
  ```
461
478
 
462
- Once initialized with sticky features, the SDK will look for values there first before evaluating the targeting conditions and going through the bucketing process.
479
+ ## Diagnostics
463
480
 
464
- ### Set sticky afterwards
481
+ The SDK reports what happens during evaluation as diagnostics, at one of five levels: `fatal`, `error`, `warn`, `info` and `debug`. By default, those at `info` and above go to the console with a `[Featurevisor]` prefix.
465
482
 
466
- Set sticky features after initialization:
483
+ `debug` shows how each value was evaluated, which helps when a result surprises you. Set the level when creating the instance, or later:
467
484
 
468
485
  ```ruby
469
- f.set_sticky_features({
470
- checkout: {
471
- enabled: true,
472
- variation: 'treatment',
473
- variables: {
474
- myVariableKey: 'myVariableValue'
475
- }
476
- },
477
- anotherFeatureKey: {
478
- enabled: false
479
- }
480
- }, true) # replace existing sticky features (false by default)
486
+ f = Featurevisor.create_featurevisor(log_level: 'debug')
481
487
 
482
- f.set_sticky_variables({ welcomeMessage: 'Welcome back' }, true)
488
+ f.set_log_level('warn')
483
489
  ```
484
490
 
485
- ## Setting datafile
486
-
487
- You may also initialize the SDK without passing `datafile`, and set it later on:
491
+ To send diagnostics somewhere other than the console, pass a handler:
488
492
 
489
493
  ```ruby
490
- # Parse with symbolized keys before setting
491
- datafile_content = JSON.parse(json_string, symbolize_names: true)
492
- f.set_datafile(datafile_content)
493
-
494
- # Or pass JSON string directly for automatic parsing
495
- f.set_datafile(json_string)
494
+ f = Featurevisor.create_featurevisor(
495
+ on_diagnostic: ->(diagnostic) {
496
+ # send diagnostic[:level], [:code], [:message] and [:details] to your observability system
497
+ }
498
+ )
496
499
  ```
497
500
 
498
- `set_datafile` returns `true` when the datafile is accepted, including unchanged content. It returns `false` when the datafile is rejected or the instance is closed. Rejected datafiles leave the last accepted datafile in place. Diagnostics and events keep their existing behaviour.
501
+ Every diagnostic has `:level`, `:code`, `:message` and a `:details` hash. Values about an evaluation, such as `featureKey`, `variableKey`, `reason` and `evaluation`, are in `:details`. `:module`, `:moduleName` and `:originalError` say where an error came from, when known. A handler that raises stops neither other handlers nor evaluations.
499
502
 
500
- Schema version `"2"` selectors normalize eagerly before merging. Schema version `"4"` entities normalize lazily on first read. Informational schema metadata is retained. Partial updates invalidate only incoming entities. Replacement clears normalized caches. Caller definitions are never changed.
503
+ ### Evaluation errors
501
504
 
502
- ### Merging by default
505
+ `conditions_parse_error` is an `error` diagnostic for malformed stringified conditions. It fires once per selector per datafile load, on first read for v4 datafiles and during `set_datafile` for v3 datafiles. Its `:details` contain `conditions` with the raw string, `entityType` and `entityKey`.
503
506
 
504
- By default, `set_datafile(datafile)` merges the incoming datafile into the SDK's current datafile:
507
+ The whole malformed selector evaluates to `false`, even under `not`, while other entities keep working and `set_datafile` returns `true` for an otherwise valid datafile. A malformed root gate is unmet and reports `conditions_unmet`.
505
508
 
506
- - top-level metadata such as `schemaVersion`, `revision`, and `featurevisorVersion` comes from the incoming datafile
507
- - `segments` are merged, with incoming entries overriding existing ones
508
- - `features` are merged, with incoming entries overriding existing ones
509
- - global `variables` are merged, with incoming entries overriding existing ones
509
+ Dependency cycles, and chains of more than 256 dependencies, fail the whole evaluation with reason `error`. SDK evaluation errors return the ordinary false or `nil` result, and other entities keep working.
510
510
 
511
- Call `set_datafile` with different datafiles to merge their features, segments, and global variables.
512
-
513
- ### Replacing
511
+ ## Evaluation details
514
512
 
515
- To fully replace the stored datafile, pass `true` as the second argument:
513
+ The `evaluate` methods return how a value was reached, not only the value:
516
514
 
517
515
  ```ruby
518
- f.set_datafile(datafile_content, true) # replace
516
+ f.evaluate_flag('checkout', context)
517
+ f.evaluate_variation('pricing', context)
518
+ f.evaluate_variable('buyButton', 'label', context)
519
+ f.evaluate_variable('supportEmail', context)
519
520
  ```
520
521
 
521
- ### Loading datafiles on demand
522
-
523
- Merge datafiles for different [targets](https://featurevisor.com/docs/targets/) into the same instance. Here, the two datafile values have already been loaded and validated by your application from the same published release:
522
+ For `user-4`, `evaluate_flag` returns:
524
523
 
525
524
  ```ruby
526
- f.set_datafile(products_datafile)
527
- f.set_datafile(checkout_datafile)
525
+ {
526
+ type: 'flag',
527
+ feature_key: 'checkout',
528
+ reason: 'rule',
529
+ bucket_key: 'user-4.checkout',
530
+ bucket_value: 89312,
531
+ rule_key: 'netherlands',
532
+ enabled: true
533
+ }
528
534
  ```
529
535
 
530
- Use immutable release URLs, check HTTP responses and keep shared dependencies consistent. See [Loading datafiles on demand](https://featurevisor.com/docs/use-cases/on-demand-datafiles/) for the complete loading and refresh flow.
536
+ Every evaluation has a `:type` and a `:reason`. Others appear when they apply:
537
+
538
+ - `:feature_key`, absent for global variables, so check for it before using it
539
+ - `:bucket_key` and `:bucket_value`, from 0 to 100,000, and the `:rule_key` that matched
540
+ - `:enabled`, `:variation` and `:variation_value`
541
+ - `:variable_key`, `:variable_value`, `:variable_schema` and `:variable`, the global variable's definition
542
+ - `:variable_override_key` and `:variable_override_index` when a keyed override matched, and `:variable_override_path` for a nested one
543
+ - `:variable_override_paths`, every override path matched in order, for [accumulating overrides](https://featurevisor.com/docs/mutations/#accumulate-overrides). The singular fields describe the last match
544
+ - `:conditions` when a [root gate](https://featurevisor.com/docs/conditions/) stopped the evaluation
545
+ - `:error` when evaluation failed
546
+
547
+ ### Evaluation reasons
548
+
549
+ [Test specs](https://featurevisor.com/docs/testing/) can assert them.
550
+
551
+ | Reason | Meaning |
552
+ | ----------------------------- | -------------------------------------------------------------------------------- |
553
+ | `feature_not_found` | The feature is not in the datafile |
554
+ | `disabled` | The feature is disabled |
555
+ | `no_variations` | A variation was requested from a feature without variations |
556
+ | `variation_disabled` | A disabled feature returned its `disabledVariationValue` |
557
+ | `variable_not_found` | The feature variable or global variable is not in the datafile |
558
+ | `variable_default` | The variable returned its default value |
559
+ | `variable_composed` | A global variable read its composition sources with no override match |
560
+ | `variable_disabled` | A disabled feature returned the variable's disabled value |
561
+ | `variable_override_variation` | A feature variable override matched inside a variation |
562
+ | `variable_override_rule` | A feature variable override or global variable override matched |
563
+ | `conditions_unmet` | Root conditions did not match. See `:conditions` |
564
+ | `no_match` | No rule, allocation or variation matched, or the bucket fell outside the rollout |
565
+ | `forced` | A `force` entry supplied the result |
566
+ | `sticky` | A sticky value supplied the result |
567
+ | `rule` | A matching rule supplied the result |
568
+ | `allocated` | Bucketing allocated the result |
569
+ | `error` | Evaluation failed. See `:error` |
531
570
 
532
- ### Updating datafile
533
-
534
- Each accepted datafile update emits a [`datafile_set`](#datafile-set) event. Subscribe to react to updates.
571
+ ## Modules
535
572
 
536
- The triggers for setting the datafile again can be:
573
+ A module hooks into evaluation. It can change the context before an evaluation, change the result after it, or decide how users are bucketed. Every part is optional:
537
574
 
538
- - periodic updates based on an interval (like every 5 minutes), or
539
- - reacting to:
540
- - a specific event in your application (like a user action), or
541
- - an event served via websocket or server-sent events (SSE)
575
+ ```ruby
576
+ audit_module = {
577
+ name: 'audit',
542
578
 
543
- ### Interval-based update
579
+ setup: ->(api) {
580
+ api[:on_diagnostic].call(->(diagnostic) {
581
+ # diagnostics at this module's own level
582
+ })
583
+ api[:report_diagnostic].call({
584
+ level: 'info',
585
+ code: 'module_ready',
586
+ message: "Ready for revision #{api[:get_revision].call}"
587
+ })
588
+ },
544
589
 
545
- Replace the complete datafile on each refresh so definitions removed upstream are removed from the SDK too. Use merging only when loading partial datafiles intentionally.
590
+ before_evaluation: ->(options) {
591
+ # :type, :feature_key, :variable_key and :context
592
+ options.merge(context: options[:context].merge(plan: 'paid'))
593
+ },
546
594
 
547
- ```ruby
548
- require 'net/http'
549
- require 'json'
595
+ after_evaluation: ->(evaluation, options) {
596
+ # log evaluation[:error] when evaluation[:reason] is 'error'
597
+ evaluation
598
+ },
550
599
 
551
- def update_datafile(f, datafile_url)
552
- loop do
553
- sleep(5 * 60) # 5 minutes
600
+ bucket_key: ->(options) { options[:bucket_key] },
554
601
 
555
- begin
556
- response = Net::HTTP.get_response(URI(datafile_url))
557
- datafile_content = JSON.parse(response.body)
558
- f.set_datafile(datafile_content, true) # replace
559
- rescue => e
560
- # handle error
561
- puts "Failed to update datafile: #{e.message}"
562
- end
563
- end
564
- end
602
+ # between 0 and 100,000
603
+ bucket_value: ->(options) { options[:bucket_value] },
565
604
 
566
- # Start the update thread
567
- Thread.new { update_datafile(f, datafile_url) }
605
+ close: -> {
606
+ # clean up when the instance closes
607
+ }
608
+ }
568
609
  ```
569
610
 
570
- ## Diagnostics
611
+ `before_evaluation` and `after_evaluation` run for flags, variations and both kinds of variable, every module in registration order, and must return the options and the evaluation, changed or not. A variable evaluation without a `:feature_key` is a global one.
571
612
 
572
- By default, Featurevisor reports diagnostics to the console for `info` level and above with a `[Featurevisor]` prefix.
613
+ `before_evaluation` also runs when a [schema](#schemas) validates, with `type` `schema` and the schema's `key` instead of a `:feature_key`, so context it adds reaches the schema's conditions too. `after_evaluation` does not run then, since a validation's result is not an evaluation. Check `type` before reading the keys.
573
614
 
574
- ### Levels
615
+ The before evaluation and after evaluation phases each use the module membership at the start of that phase, and the bucket key and bucket value phases each use their own. Adding or removing a module during a phase does not change the iteration already in progress.
575
616
 
576
- Available diagnostic levels are `fatal`, `error`, `warn`, `info`, and `debug`.
617
+ If `setup` raises, the module is not registered. The SDK removes the diagnostic subscriptions it made, reports `module_setup_error`, and calls its `close` if it has one.
577
618
 
578
- Set the level during initialization or update it afterwards:
619
+ ### Dependency evaluations
579
620
 
580
- ```ruby
581
- f = Featurevisor.create_featurevisor(log_level: "debug")
582
- f.set_log_level("info")
583
- ```
621
+ [Conditions](https://featurevisor.com/docs/conditions/) and [composition members](https://featurevisor.com/docs/variables/#compose-values) are evaluated through modules too. Their options include `:dependency_of`, naming the requesting evaluation by `type`, `feature_key` and `variable_key`. `:dependency_purpose` is `'condition'` for an eligibility check and `'composition'` for a consumed member value. Direct calls have neither.
622
+
623
+ When tracking consumed evaluations, skip eligibility checks, not every read with `:dependency_of`, since a variation read through a composition can be an experiment exposure. Within one call, repeated reads with the same inputs and purpose are memoized, so callbacks can run fewer times than there are reads. Return the same result for the same input during one evaluation, and pass values that change through the context.
584
624
 
585
- ### Handler
625
+ ### Register a module
586
626
 
587
- Use `on_diagnostic` to send structured diagnostics to your observability system:
627
+ Pass modules when creating the instance, or add them later:
588
628
 
589
629
  ```ruby
590
630
  f = Featurevisor.create_featurevisor(
591
- log_level: "info",
592
- on_diagnostic: ->(diagnostic) {
593
- puts "#{diagnostic[:level]} #{diagnostic[:code]} #{diagnostic[:message]}"
594
- }
631
+ modules: [audit_module]
595
632
  )
596
- ```
597
633
 
598
- Every diagnostic has `:level`, `:code`, `:message`, and an object-shaped `:details` hash. Optional `:module`, `:moduleName`, and `:originalError` fields describe provenance. Evaluation metadata belongs in `:details`.
634
+ remove = f.add_module(tracking_module)
599
635
 
600
- Diagnostic handlers are isolated from SDK behaviour. An exception in a handler does not stop other handlers or evaluations.
636
+ # later
637
+ remove.call
638
+ f.remove_module('audit')
639
+ ```
601
640
 
602
- Malformed stringified selectors report `conditions_parse_error` at error level once per selector per incoming entity load. Details contain exactly `conditions` with the original string, `entityType` and `entityKey`. Schema 2 diagnostics run after accepted datafile storage. V4 diagnostics run after caching the first entity read. Handlers may safely read the accepted revision again. A malformed selector fails locally, even through NOT or segment references, without rejecting the datafile or disabling unrelated entities.
641
+ ### Read the datafile from a module
603
642
 
604
- ## Events
643
+ A package, such as [schemas](#schemas), reads the datafile through the API `setup` receives:
605
644
 
606
- Subscribe to SDK events to respond to context, sticky state and datafile changes.
645
+ - `api[:get_entry].call(section, key)` returns an entry of a section, a top level key besides Featurevisor's own whose value is an object, such as `schemas`, with symbol keys. Treat it as read only. `api[:get_entry_keys]` lists a section's keys.
646
+ - `api[:match_conditions]` answers the package's own conditions with the instance's engine, segments and feature leaves included. Its `readers` answer leaves only the package knows, such as `input`, returning `Featurevisor::Conditions.missing_value` for no value.
647
+ - `api[:evaluate].call({ type:, key:, context: }) { |scope| ... }` evaluates the package's own entry as a getter evaluates a flag. Every module's `before_evaluation` runs first, with `type` and `key` naming the entry, and the conditions the block answers with `scope.match_conditions(conditions, readers)` read the context the modules leave, in one dependency session. The block's result is returned.
607
648
 
608
- Subscribe to instance lifecycle events:
649
+ Feature and variable leaves reach modules as dependencies, with `:dependency_of` naming the package's entry. A module with no evaluation callbacks, such as a package's, costs evaluations nothing.
609
650
 
610
- ### `datafile_set`
651
+ ## Schemas
611
652
 
612
- ```ruby
613
- unsubscribe = f.on('datafile_set') do |event|
614
- revision = event[:revision] # new revision
615
- previous_revision = event[:previousRevision]
616
- revision_changed = event[:revisionChanged] # true if revision has changed
653
+ Schemas validate data against the [schemas](https://featurevisor.com/docs/schemas/#validate-application-data) your datafiles deliver, with the instance you already have, and the same rules, messages and conditions as `@featurevisor/schemas` in JavaScript.
617
654
 
618
- # list of feature keys that have new updates,
619
- # and you should re-evaluate them
620
- features = event[:features]
655
+ Schemas are experimental, so their API may change in a minor release, as in JavaScript.
621
656
 
622
- # handle here
623
- end
657
+ ### Create a schemas instance
624
658
 
625
- # stop listening to the event
626
- unsubscribe.call
659
+ They are a separate gem, released with the same version as the SDK:
660
+
661
+ ```ruby
662
+ gem 'featurevisor-schemas', '~> 4.1'
627
663
  ```
628
664
 
629
- The `features` and `variables` arrays include direct changes and transitive dependencies through conditions, segments and composition sources. They contain entities that have been:
665
+ Create it from the SDK instance. Call it `s`, as the SDK instance is `f`:
630
666
 
631
- - added, or
632
- - updated, or
633
- - removed
667
+ ```ruby
668
+ require 'featurevisor-schemas'
634
669
 
635
- compared to the previous datafile content that existed in the SDK instance.
670
+ s = Featurevisor::Schemas.create(f)
671
+ ```
636
672
 
637
- The event also includes `replaced`, which is `true` when the datafile replaced the previous content instead of merging into it.
673
+ It holds no copy of the schemas. Every call reads the datafile `f` has now, so a [new datafile](#update-the-datafile) applies at the next validation. Compiled schemas are kept until a datafile changes them, and handles are safe to share between threads.
638
674
 
639
- ### `context_set`
675
+ ### Validate a value
640
676
 
641
677
  ```ruby
642
- unsubscribe = f.on('context_set') do |event|
643
- replaced = event[:replaced] # true if context was replaced
644
- context = event[:context] # the new context
678
+ value = {
679
+ email: 'user-1@example.com',
680
+ displayName: 'A',
681
+ country: 'nl'
682
+ }
645
683
 
646
- puts 'Context set'
684
+ result = s.validate('signUp', value)
685
+
686
+ unless result.valid?
687
+ # show result.issues beside the form's fields
647
688
  end
648
689
  ```
649
690
 
650
- ### `sticky_features_set` and `sticky_variables_set`
691
+ - `s.validate(key, value)` returns a result with the value itself and its `issues`. It never coerces, fills defaults or strips keys.
692
+ - `s.valid?(key, value)` returns a boolean.
693
+ - `s.parse(key, value)` returns the value, or raises `Featurevisor::Schemas::ValidationError`, for a controller or a script that wants a value or a stop.
694
+ - All three take `context:`, merged over the instance's, for the [conditions](https://featurevisor.com/docs/schemas/#read-the-context) a schema's rules read.
695
+ - A validation runs as the schema's own evaluation, so a [module](#modules)'s `before_evaluation` sees it, with `type` `schema` and the schema's `key`, and context the module adds reaches every condition, as it does for flags.
696
+ - `s.keys` lists the schemas the datafile has, and `s.key?(key)` says whether it has one.
651
697
 
652
- ```ruby
653
- feature_unsubscribe = f.on('sticky_features_set') do |event|
654
- replaced = event[:replaced] # true if sticky features got replaced
655
- features = event[:features] # list of all affected feature keys
698
+ A value can be hashes with string or symbol keys, arrays and primitives, or a `Struct`.
656
699
 
657
- puts 'Sticky features set'
658
- end
700
+ A key the datafile does not have fails closed, with one `schemaNotFound` issue, and a `schema_not_found` [diagnostic](#diagnostics) at `warn`, once per key and datafile. A field the schema lacks reports its `schemaNotFound` issue alone, since the schema is there. `s.get` keeps no handle for a key the datafile lacks.
659
701
 
660
- variable_unsubscribe = f.on('sticky_variables_set') do |event|
661
- variables = event[:variables]
662
- end
663
- ```
702
+ ### Read the issues
664
703
 
665
- ### `error`
704
+ Every issue has a `message`, a `path` of object keys and array indices, the `code` of the rule that failed, its `params`, and the `schema` validated. `issue.field` gives its path as a form names a field, such as `items.0.name`.
666
705
 
667
- ```ruby
668
- unsubscribe = f.on('error') do |event|
669
- diagnostic = event[:diagnostic]
670
- code = diagnostic[:code]
671
- message = diagnostic[:message]
706
+ Validation reports every issue it finds, so a form can mark every field at once. An issue about a field with a [title](https://featurevisor.com/docs/schemas/#title-the-fields) carries it in `params[:title]`, and one whose rule a [mutation](https://featurevisor.com/docs/schemas/#mutations) set names it in `mutation`.
672
707
 
673
- puts "Featurevisor error: #{code} #{message}"
674
- end
675
- ```
708
+ | Code | Raised when |
709
+ | ---------------------------------- | --------------------------------------------------------------------- |
710
+ | `type` | The value has another type |
711
+ | `const`, `enum` | The value is not one allowed |
712
+ | `minimum`, `maximum` | A number is out of range |
713
+ | `minLength`, `maxLength` | A string is too short or too long |
714
+ | `pattern`, `format` | A string has the wrong shape |
715
+ | `minItems`, `maxItems` | An array has too few or too many items |
716
+ | `uniqueItems` | An array repeats an item |
717
+ | `required`, `additionalProperties` | A key is missing, or there is one it does not allow |
718
+ | `oneOf` | No branch matches, or more than one does |
719
+ | `refine` | An `issues` entry matches, or a [check in code](#check-in-code) fails |
720
+ | `refineError` | A check in code raises, or the schema itself cannot be applied |
721
+ | `schemaNotFound` | The datafile has no such schema or field |
676
722
 
677
- The `error` event is emitted for diagnostics reported with `level: "error"`.
723
+ `result.flatten` groups the messages by field, in the shape of Zod's `flattenError`, and so does `flatten` on a `ValidationError`, for an error response.
678
724
 
679
- ## Evaluation details
725
+ ### Get a handle
680
726
 
681
- Inspect how variations and variables are evaluated against a context:
727
+ A handle is one schema as an object your code holds: it validates, and describes the schema's fields, constraints, choices and annotations for a form. `s.get(key)` gives one:
682
728
 
683
729
  ```ruby
684
- # flag
685
- evaluation = f.evaluate_flag(feature_key, context = {})
730
+ sign_up = s.get('signUp')
731
+ ```
686
732
 
687
- # variation
688
- evaluation = f.evaluate_variation(feature_key, context = {})
733
+ A handle is stable, and reads the current datafile whenever it is used, so keep one for the life of the application.
689
734
 
690
- # variable
691
- evaluation = f.evaluate_variable(feature_key, variable_key, context = {})
735
+ | Member | What it is |
736
+ | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
737
+ | `validate`, `valid?`, `parse` | As on `s`, without the key |
738
+ | `field(path)` | The handle of one field, such as `field('displayName')` |
739
+ | `fields` | An object's fields' handles, in [order](#read-annotations), each with its `name` |
740
+ | `constraints`, `field_constraints` | HTML validation attributes, and `field_constraints` by field path on an object, [below](#read-constraints-and-choices) |
741
+ | `options`, `field_options`, `option(value)` | Its choices, `field_options` by field path on an object, and one choice by value |
742
+ | `render_as` | What its rules say the field renders as, such as `'select'` |
743
+ | `annotations` | Its [annotations](#read-annotations) |
744
+ | `with_input(input)` | The same handle with an [input](#follow-the-values-typed-so-far) |
745
+ | `reads` | The fields its rules' conditions read |
746
+ | `subscribe { }` | A call when a [new datafile](#listen-for-changes) changes the schema |
747
+ | `key`, `path`, `name` | The schema's key, and the field's path and own name |
692
748
 
693
- # global variable
694
- global_evaluation = f.evaluate_variable(variable_key, context = {})
695
- ```
749
+ `field` takes a field name as form libraries write it: `address.city`, `items.0.name` or `items[0].name`, and `items[].name` for every item alike. It follows references and stops at `oneOf`. A path the schema lacks fails closed with `schemaNotFound`.
696
750
 
697
- The returned object will always contain the following properties:
698
-
699
- - `feature_key`: the feature key when evaluating a feature
700
- - `reason`: the reason how the value was evaluated
701
-
702
- And optionally these properties depending on whether you are evaluating a feature variation or a variable:
703
-
704
- - `bucket_value`: the bucket value between 0 and 100,000
705
- - `rule_key`: the rule key
706
- - `error`: the error object
707
- - `enabled`: if feature itself is enabled or not
708
- - `variation`: the variation object
709
- - `variation_value`: the variation value
710
- - `variable_key`: the variable key
711
- - `variable_value`: the variable value
712
- - `variable_schema`: the variable schema
713
- - `variable_override_index`: index of the final matched global variable override
714
- - `variable_override_key`: key of the final matched global variable override
715
- - `variable_override_path`: authoring path of the final matched global variable override
716
- - `variable_override_paths`: all matched authoring paths from an accumulating override
717
- - `conditions`: the normalized root expression when its gate is unmet
718
- - `variable`: the global variable definition when applicable
751
+ ### Read constraints and choices
719
752
 
720
- ## Modules
753
+ `constraints` are named after HTML attributes:
721
754
 
722
- The before evaluation and after evaluation phases each use the module membership at the start of that phase. Where an evaluation uses bucketing, the bucket key and bucket value phases each use their own starting membership. Adding or removing a module during a phase does not change the iteration already in progress. The next phase uses the membership then installed. A module added before the after phase can receive after callbacks for evaluations already in progress, even if it did not receive their before callbacks. A module removed before the after phase receives no after callback.
755
+ ```ruby
756
+ sign_up.field('displayName').constraints
757
+ # required: true, min_length: 2, max_length: 40
723
758
 
724
- Module options expose `dependency_of` and `dependency_purpose` on internal reads. The requester contains `type`, optional `feature_key` and optional `variable_key`. Purpose is `condition` for gating reads or `composition` for consumed source values. Application calls have neither marker. Tracking modules can skip condition reads while retaining composition exposures.
759
+ sign_up.field('displayName').constraints.attributes
760
+ # { required: true, minlength: 2, maxlength: 40 }, for a view
761
+ ```
725
762
 
726
- Equivalent dependency reads are memoized within one public call, separating purpose, requester, effective context and current SDK state. Condition snapshots are owned. Composition values retain ordinary getter ownership. Callback options do not retain private sessions. Independent public getters called from callbacks start fresh sessions.
763
+ - `required`, when the key is required, so an input left empty fails. A key `required` lists counts, whether or not `properties` holds it, so an object with `additionalProperties` only, or none at all, still reports each missing key as `required`
764
+ - `min_length` and `max_length`, from the same rules on a string
765
+ - `min` and `max`, from `minimum` and `maximum` on a number
766
+ - `step` of 1, for an `integer`
767
+ - `multiple`, for an array, such as a multiple select
727
768
 
728
- Modules can intercept evaluation and participate in SDK lifecycle. The canonical callbacks are `setup`, `bucket_key`, `bucket_value`, `before_evaluation`, `after_evaluation`, and `close`.
769
+ `options` lists a field's choices in the order of its rules, each with what its [annotations](https://featurevisor.com/docs/schemas/#label-the-choices) say, and `option(value)` finds one, for showing a value saved earlier:
729
770
 
730
- `before_evaluation` and `after_evaluation` run for feature and global variable evaluations. Condition and composition dependency getters use the same module pipeline, while an accumulating override publishes only its final result to `after_evaluation`.
771
+ ```ruby
772
+ country = sign_up.field('country')
731
773
 
732
- ### Defining a module
774
+ country.options # nl, de and be, each with its fields
775
+ country.option('nl').title # 'Netherlands'
776
+ country.option('fr') # nil
777
+ ```
733
778
 
734
- A module is a simple hash with a unique recommended `name` and optional lifecycle functions:
779
+ A schema the datafile lacks has no constraints and no choices, so a form renders before its datafile arrives. `render_as` answers the switch every generic form writes, from the field's rules alone: `'text'`, `'date-time'`, `'version'`, `'number'`, `'boolean'`, `'select'`, `'multiselect'`, `'object'` or `'list'`. Your own annotation, such as `input: select`, still wins over it.
735
780
 
736
- If `setup` raises an exception, the module is not registered. Featurevisor removes subscriptions created during setup, reports `module_setup_error`, and calls `close` when present.
781
+ ### Read annotations
782
+
783
+ A handle's `annotations` are its node's own, and `fields` gives an object's fields in its `order`:
737
784
 
738
785
  ```ruby
739
- require 'featurevisor'
786
+ sign_up.annotations['title'] # 'Create your account'
740
787
 
741
- my_custom_module = {
742
- # recommended, and used for duplicate detection/removal
743
- name: 'my-custom-module',
788
+ sign_up.fields.map(&:path)
789
+ # ['displayName', 'email', 'country']
790
+ ```
744
791
 
745
- # rest of the properties below are all optional per module
792
+ `default` is the value a form starts a field with, and a handle from `with_input` has the one a [mutation sets](https://featurevisor.com/docs/schemas/#start-a-field-with-a-value). Fields an `order` annotation leaves out come after it, in name order by Unicode code point, as in every SDK. A field or schema the datafile lacks has no annotations, `{}`. [Annotations](https://featurevisor.com/docs/schemas/#annotations) on Schemas writes them.
746
793
 
747
- # setup once, when the module is registered
748
- setup: ->(api) {
749
- revision = api[:get_revision].call
794
+ ### Follow the values typed so far
750
795
 
751
- api[:on_diagnostic].call(->(diagnostic) {
752
- puts diagnostic[:message]
753
- })
754
- },
796
+ A handle's constraints and choices describe the schema's own rules, which no condition changes. `with_input(input)` gives the same handle with an input, such as a form's values, with the [mutations](https://featurevisor.com/docs/schemas/#mutations) that match it applied, so a tax ID shows as required once a business account is chosen:
755
797
 
756
- # before feature or global variable evaluation
757
- before_evaluation: ->(options) {
758
- # update context before evaluation
759
- options[:context] = options[:context].merge({
760
- someAdditionalAttribute: 'value'
761
- })
762
- options
763
- },
798
+ ```ruby
799
+ values = {
800
+ accountType: 'business',
801
+ country: 'nl'
802
+ }
764
803
 
765
- # after feature or global variable evaluation
766
- after_evaluation: ->(evaluation, options) {
767
- reason = evaluation[:reason]
768
- if reason == 'error'
769
- # log error
770
- end
771
- evaluation
772
- },
804
+ sign_up.field('taxId').constraints.required # false
805
+ sign_up.with_input(values).field('taxId').constraints.required # true
806
+ ```
773
807
 
774
- # configure bucket key
775
- bucket_key: ->(options) {
776
- # return custom bucket key
777
- options[:bucket_key]
778
- },
808
+ Every member follows the input, at every depth. `reads` lists the fields the conditions of a handle's mutations and issues read, so a form can validate again only when one of them changes.
779
809
 
780
- # configure bucket value (between 0 and 100,000)
781
- bucket_value: ->(options) {
782
- # return custom bucket value
783
- options[:bucket_value]
784
- },
810
+ ### Choose the messages
785
811
 
786
- # cleanup when module is removed or SDK is closed
787
- close: -> {
788
- # cleanup here
812
+ `messages:` on `create` words every schema's issues, per code, as a template or a lambda of the params:
813
+
814
+ ```ruby
815
+ s = Featurevisor::Schemas.create(
816
+ f,
817
+ messages: {
818
+ required: 'This field is required',
819
+ maxLength: ->(params, info) { "#{params[:length]} of #{params[:maxLength]} characters" }
789
820
  }
790
- }
821
+ )
791
822
  ```
792
823
 
793
- The module API passed to `setup` exposes:
794
-
795
- - `get_revision`
796
- - `on_diagnostic`
797
- - `report_diagnostic`
824
+ `messages:` on `s.get` words one form, by field and code, such as `{ displayName: { maxLength: 'Names fit {maxLength} characters' } }`. For each issue, the first of these that words it wins:
798
825
 
799
- ### Registering modules
826
+ 1. A check in code's own message, then the form's.
827
+ 2. The schema's own, and then the `message` of its [issues](https://featurevisor.com/docs/schemas/#issues) entry.
828
+ 3. The application's, from `messages:` on `create`.
829
+ 4. The default, in English.
800
830
 
801
- Register modules when you create the instance:
831
+ `translate:` on `create` gets each issue, with the message chosen, and returns what the issue says, or `nil` to keep it. With translations, `messages:` holds keys, such as `errors.required`, and `translate:` turns each into text:
802
832
 
803
833
  ```ruby
804
- require 'featurevisor'
805
-
806
- f = Featurevisor.create_featurevisor(
807
- modules: [my_custom_module]
834
+ s = Featurevisor::Schemas.create(
835
+ f,
836
+ translate: ->(issue, info) { I18n.t(issue.message, **issue.params, default: nil) }
808
837
  )
809
838
  ```
810
839
 
811
- Or after initialization:
840
+ ### Check in code
841
+
842
+ Some checks need your application, such as whether a display name is taken. Give them to a handle in `refine:`, each a `Refinement` with a `key` and a `check`, and the `path` it checks, a `message` and `reads` as it needs them:
812
843
 
813
844
  ```ruby
814
- remove_module = f.add_module(my_custom_module)
845
+ sign_up = s.get('signUp', refine: [
846
+ Featurevisor::Schemas::Refinement.new(
847
+ key: 'nameAvailable',
848
+ path: 'displayName',
849
+ check: ->(display_name, info) { !User.exists?(display_name: display_name) },
850
+ message: 'That display name is taken'
851
+ )
852
+ ])
853
+
854
+ result = sign_up.validate(value)
855
+ ```
815
856
 
816
- # remove later by calling the returned function
817
- remove_module.call
857
+ - `check` gets the value at its path, and `info` with the whole `input` and the `context`, where `info.read('country')` reads another field. It returns `true` when the value passes.
858
+ - It runs after the schema's rules, and only when nothing at or inside its path has an issue already, so a name that is too short never reaches your database.
859
+ - Without a `path`, the check gets the whole value, and runs only when the value has no issue at all. `reads` names other fields whose issues hold it back too, such as `items` for a check of an order's total.
860
+ - Its issue has code `refine` and `params[:refine]` `'nameAvailable'`, with the field's title. A check that raises gives `refineError`, and validation fails closed.
861
+ - Checks run in order, synchronously.
818
862
 
819
- # or remove by name
820
- f.remove_module('my-custom-module')
821
- ```
863
+ ### Options from your application
822
864
 
823
- ## Child instance
865
+ Some lists only your application can answer for, such as cities for a `city` field. Give a handle an `OptionSource` in `option_sources:`, with a `key`, a `path`, and a `search`, a `lookup` or both:
824
866
 
825
- A child snapshots the parent keys that exist when it is spawned. Child values win for those keys. Parent keys introduced later are still inherited. Calling `close` removes both child-owned listeners and subscriptions delegated to the parent.
867
+ ```ruby
868
+ cities = Featurevisor::Schemas::OptionSource.new(
869
+ key: 'cities',
870
+ path: 'city',
871
+ reads: ['country'],
872
+ search: ->(query, info) { City.where(country: info.read('country')).search(query).map(&:name) },
873
+ lookup: ->(city, info) { City.find_by(country: info.read('country'), name: city)&.then { |found| { title: found.name } } },
874
+ message: 'Choose a city from the list'
875
+ )
826
876
 
827
- When dealing with purely client-side applications, it is understandable that there is only one user involved, like in browser or mobile applications.
877
+ sign_up = s.get('signUp', option_sources: [cities])
878
+ city = sign_up.with_input({ country: 'nl' }).field('city')
828
879
 
829
- But when using Featurevisor SDK in server-side applications, where a single server instance can handle multiple user requests simultaneously, it is important to isolate the context for each request.
880
+ city.search('am')
881
+ # Amsterdam and Amersfoort
882
+ ```
830
883
 
831
- That's where child instances come in handy:
884
+ - `search` returns choices shaped like `options`, or values alone. A handle's `search` passes it the values given to `with_input`, so the cities follow the country. `searchable?` says whether a field has one.
885
+ - `lookup` returns the choice for a value, `true` when it carries nothing more, or `nil` when there is none. A handle's `lookup(value)` returns the schema's own choice first, then the source's.
886
+ - Validation runs `lookup` as a [check in code](#check-in-code), after the schema's rules, only for a value that is there, and not while a field `reads` names has an issue. A value it cannot find has code `enum`, worded by `message`.
887
+
888
+ ### Validate on the server
889
+
890
+ `parse` answers a request with a value or a `ValidationError`, whose `flatten` gives the issues by field:
832
891
 
833
892
  ```ruby
834
- child_f = f.spawn({
835
- # user or request specific context
836
- userId: '123'
837
- })
893
+ class SignUpsController < ApplicationController
894
+ def create
895
+ value = Featurevisor.schemas.parse('signUp', params.to_unsafe_h)
896
+ render json: create_account(value)
897
+ rescue Featurevisor::Schemas::ValidationError => error
898
+ render json: error.flatten, status: :bad_request
899
+ end
900
+ end
838
901
  ```
839
902
 
840
- Pass the child instance to the request handler to evaluate features for that user:
903
+ `Featurevisor.schemas` stands for wherever your application keeps `s`. A rule changed in your project reaches the browser and the server at their next datafile, so the two never disagree.
904
+
905
+ ### Listen for changes
906
+
907
+ `subscribe` calls its block when a new datafile changes the schema, through a schema it references too, and returns a lambda that stops it:
841
908
 
842
909
  ```ruby
843
- is_enabled = child_f.is_enabled('checkout')
844
- variation = child_f.get_variation('checkout')
845
- variable_value = child_f.get_variable('checkout', 'bgColor')
846
- global_value = child_f.get_variable('welcomeMessage')
910
+ stop = s.get('signUp').field('country').subscribe { render_choices }
847
911
  ```
848
912
 
849
- Similar to parent SDK, child instances also support several additional methods:
850
-
851
- - `set_context`
852
- - `set_sticky_features`
853
- - `set_sticky_variables`
854
- - `evaluate_flag`
855
- - `is_enabled`
856
- - `evaluate_variation`
857
- - `get_variation`
858
- - `evaluate_variable`
859
- - `get_variable`
860
- - `get_variable_boolean`
861
- - `get_variable_string`
862
- - `get_variable_integer`
863
- - `get_variable_number`
864
- - `get_variable_array`
865
- - `get_variable_object`
866
- - `get_variable_json`
867
- - `get_feature_evaluations`
868
- - `get_variable_evaluations`
869
- - `on`
870
- - `close`
913
+ A datafile whose schema is unchanged calls nothing. `s.close` stops every listener the instance started and removes its module from the Featurevisor instance.
871
914
 
872
- ## Close
915
+ ### Patterns
916
+
917
+ Schema patterns are JavaScript regular expressions with the `u` flag, and they mean the same here: `^` and `$` are the start and end of the value, `\s` is JavaScript's whitespace, and `.` reads an emoji as one character, as lengths do. A pattern that does not compile with `u`, such as `[a-z\_]`, fails every value, as does a `type` the package does not know, which reports a `type` issue.
873
918
 
874
- Both primary and child instances support a `.close()` method. It removes event listeners and child subscriptions. The primary instance also closes modules, clears diagnostic subscriptions and parsed expression caches, and releases its diagnostic handler after reporting any module shutdown errors. Closing is idempotent.
919
+ ### Failing closed
875
920
 
876
- Ruby can collect unreachable reference cycles, but objects still referenced by your application remain alive. Call unsubscribe functions when finished with individual subscriptions, and close instances and children when finished with them. Retained instance handles still own their datafiles and context. Closing does not promise that every allocation is returned to the operating system.
921
+ A schema that fails values closed says why with an `error` [diagnostic](#diagnostics), once per datafile revision, so a new datafile reports again:
922
+
923
+ - `schema_pattern_unsupported`, for a pattern that does not compile.
924
+ - `schema_mutation_error`, with `refineError`, for a mutation whose operations cannot be applied.
925
+ - `schema_reference_depth`, with `refineError`. Validation follows at most 128 references inside one another, which limits how deep a value can nest through them: a tree whose nodes each reference the tree's schema can be 128 levels deep, and the node at the 129th fails closed. The message reads `Schema "tree" fails the value closed, since the value is nested more than 128 references deep.`
926
+ - `schema_check_error`, with `refineError`, for a [check in code](#check-in-code) or an option source's `lookup` that raises. Its `details` hold `schemaKey`, `check`, the check's key, and `path`, the check's path as written or an empty string, and the diagnostic carries the `originalError`. It is reported once per schema and check.
927
+
928
+ ### Fields validated alone
929
+
930
+ A field's handle validates the field's value, so a check's `info.input` in a handle from `field` is the field's value, and only checks that read no other field run there. A handle from the schema's root with `with_input`, such as `with_input(values).field('city')`, gives the whole input. Ruby has no way to give a field handle no value, since `nil` is JSON null, which is a value, so a field validated with `nil` is checked as null and not read as absent.
931
+
932
+ The message translator, `translate:`, runs last, once mutations have named the issues whose rules they set or changed, so it sees `issue.mutation`.
933
+
934
+ ## Close
935
+
936
+ `close` removes event listeners and closes modules, on the instance and on a child. Closing twice does nothing more:
877
937
 
878
938
  ```ruby
879
- f.close()
939
+ f.close
880
940
  ```
881
941
 
942
+ Ruby collects unreachable cycles, but an instance your application still references stays alive, so close instances and children when you are done with them.
943
+
882
944
  ## OpenFeature
883
945
 
884
946
  The OpenFeature provider is published as a separate gem. This keeps OpenFeature code and dependencies out of applications that only use the Featurevisor SDK.
@@ -908,11 +970,11 @@ client = OpenFeature::SDK.build_client
908
970
  enabled = client.fetch_boolean_value(
909
971
  flag_key: "checkout",
910
972
  default_value: false,
911
- evaluation_context: OpenFeature::SDK::EvaluationContext.new(targeting_key: "user-123"),
973
+ evaluation_context: OpenFeature::SDK::EvaluationContext.new(targeting_key: "user-4"),
912
974
  )
913
975
  ```
914
976
 
915
- Use `checkout` for a flag, `checkout:variation` for its variation, `checkout:title` for its `title` variable, and `variable:welcomeMessage` for a global variable. Boolean variables use the boolean resolver. Arrays, hashes, and JSON variables use the object resolver.
977
+ Use `checkout` for a flag, `checkout:variation` for its variation, `buyButton:label` for its `label` variable, and `variable:supportEmail` for a global variable. Boolean variables use the boolean resolver. Arrays, hashes, and JSON variables use the object resolver.
916
978
 
917
979
  OpenFeature's targeting key maps to `userId` by default. `targeting_key_field`, `key_separator`, `variation_key`, and `global_variable_prefix` can customize the mapping. The global variable prefix defaults to `variable` and cannot contain the separator.
918
980
 
@@ -944,7 +1006,7 @@ See the [OpenFeature provider guide](https://featurevisor.com/docs/sdks/openfeat
944
1006
 
945
1007
  ## CLI usage
946
1008
 
947
- After adding the gem to your Gemfile as shown in [Installation](#installation), install it with:
1009
+ After adding the gem to your Gemfile as shown in [Install](#install), install it with:
948
1010
 
949
1011
  ```bash
950
1012
  bundle install
@@ -952,7 +1014,7 @@ bundle install
952
1014
 
953
1015
  Use `bundle exec featurevisor` for a bundled installation, `featurevisor` for a global gem installation, or `bin/featurevisor` from this SDK repository.
954
1016
 
955
- The native test runner requires `@featurevisor/cli` 4.0.0 or later and Node.js 24 or later. Install the Node.js CLI in your Featurevisor project:
1017
+ The native test runner requires Node.js 24 or later. Install the Node.js CLI in your Featurevisor project:
956
1018
 
957
1019
  ```bash
958
1020
  npm install --save-dev @featurevisor/cli@^4.0.0
@@ -979,7 +1041,7 @@ See [Testing](https://featurevisor.com/docs/testing/) for authoring specs and [C
979
1041
  Useful test options:
980
1042
 
981
1043
  - `--key-pattern=<pattern>` and `--assertion-pattern=<pattern>` filter tests.
982
- - `--entity-type=scenario` selects scenarios. `--set=<set>` selects one project set. Omitting `--set` runs all sets.
1044
+ - `--entity-type=scenario` selects scenarios, and `--entity-type=schema` schema specs, which validate their values with the `featurevisor-schemas` gem as the JavaScript CLI does. Without that gem, each schema spec case fails asking for it. `--set=<set>` selects one project set. Omitting `--set` runs all sets.
983
1045
  - `--case=<id>` reruns one expanded case. Copy the opaque ID or rerun command from a failure report.
984
1046
  - `--json --pretty` produces an indented JSON report.
985
1047
  - `--coverage` reports observed rule and override selections. `--uncovered` lists features and global variables without associated specs.
@@ -1025,12 +1087,14 @@ Repeat `--populate-uuid=<key>` to generate UUID values for multiple context attr
1025
1087
  <!-- FEATUREVISOR_DOCS_END -->
1026
1088
 
1027
1089
  <a id="getting-aggregate-evaluations"></a>
1090
+ <a id="getting-evaluations"></a>
1028
1091
 
1029
- The aggregate evaluation reference has moved to [Getting evaluations](#getting-evaluations).
1092
+ The aggregate evaluation reference has moved to [Evaluate everything at once](#evaluate-everything-at-once).
1030
1093
 
1031
1094
  <a id="sticky-features-and-variables"></a>
1095
+ <a id="sticky"></a>
1032
1096
 
1033
- The sticky state reference has moved to [Sticky](#sticky).
1097
+ The sticky state reference has moved to [Sticky values](#sticky-values).
1034
1098
 
1035
1099
  ## Development
1036
1100
 
@@ -1054,11 +1118,11 @@ Build and verify both gems with:
1054
1118
  $ make build
1055
1119
  ```
1056
1120
 
1057
- The build produces `featurevisor-VERSION.gem` and `featurevisor-openfeature-VERSION.gem`. The artifact verifier confirms that OpenFeature code and dependencies are absent from the base gem and present only in the provider gem.
1121
+ The build produces `featurevisor-VERSION.gem`, `featurevisor-schemas-VERSION.gem` and `featurevisor-openfeature-VERSION.gem`. The artifact verifier confirms that OpenFeature code and dependencies are absent from the base gem and present only in the provider gem.
1058
1122
 
1059
1123
  ### Releasing
1060
1124
 
1061
- The next breaking release is `4.0.0` for both gems. Keep both Gemfile lockfiles aligned with the shared version. Run `make test`, `make test-base` and `make build` before tagging. The artefact check verifies the provider's exact dependency on the base gem and their separate contents.
1125
+ The next release is `4.1.0` for all three gems. Keep both Gemfile lockfiles aligned with the shared version. Run `make test`, `make test-base` and `make build` before tagging. The artefact check verifies the provider's exact dependency on the base gem and their separate contents.
1062
1126
 
1063
1127
  - Update the shared version in `lib/featurevisor/version.rb`
1064
1128
  - Run `bundle install`