standard_flags 0.1.0 → 0.2.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.
Files changed (71) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +229 -0
  3. data/README.md +837 -33
  4. data/lib/generators/standard_flags/admin/admin_generator.rb +115 -0
  5. data/lib/generators/standard_flags/admin/templates/controller.rb.tt +103 -0
  6. data/lib/generators/standard_flags/admin/templates/index.tsx.tt +64 -0
  7. data/lib/generators/standard_flags/admin/templates/show.tsx.tt +275 -0
  8. data/lib/generators/standard_flags/install/install_generator.rb +16 -1
  9. data/lib/generators/standard_flags/install/templates/flags.rb.tt +3 -2
  10. data/lib/generators/standard_flags/install/templates/initializer.rb.tt +10 -0
  11. data/lib/generators/standard_flags/migrations/migrations_generator.rb +57 -0
  12. data/lib/generators/standard_flags/migrations/templates/create_standard_flags_tables.rb.tt +78 -0
  13. data/lib/standard_flags/actor.rb +50 -0
  14. data/lib/standard_flags/audit_trail.rb +56 -0
  15. data/lib/standard_flags/config.rb +78 -0
  16. data/lib/standard_flags/context.rb +5 -1
  17. data/lib/standard_flags/definition.rb +85 -13
  18. data/lib/standard_flags/diagnostics.rb +35 -3
  19. data/lib/standard_flags/engine.rb +10 -2
  20. data/lib/standard_flags/env_pin.rb +15 -4
  21. data/lib/standard_flags/errors.rb +4 -0
  22. data/lib/standard_flags/evaluation.rb +5 -4
  23. data/lib/standard_flags/evaluator.rb +14 -1
  24. data/lib/standard_flags/events.rb +49 -0
  25. data/lib/standard_flags/health_check.rb +12 -2
  26. data/lib/standard_flags/health_contribution.rb +65 -0
  27. data/lib/standard_flags/mcp/cohorts.rb +65 -0
  28. data/lib/standard_flags/mcp/flags.rb +143 -0
  29. data/lib/standard_flags/mcp/members.rb +154 -0
  30. data/lib/standard_flags/mcp/writes.rb +98 -0
  31. data/lib/standard_flags/mcp.rb +238 -0
  32. data/lib/standard_flags/memo.rb +15 -1
  33. data/lib/standard_flags/notifiers/logger.rb +14 -0
  34. data/lib/standard_flags/open_feature/provider.rb +232 -0
  35. data/lib/standard_flags/open_feature.rb +26 -0
  36. data/lib/standard_flags/operations/audit.rb +218 -0
  37. data/lib/standard_flags/operations/base.rb +290 -0
  38. data/lib/standard_flags/operations/cohorts.rb +80 -0
  39. data/lib/standard_flags/operations/failure.rb +16 -0
  40. data/lib/standard_flags/operations/members.rb +164 -0
  41. data/lib/standard_flags/operations/restore.rb +330 -0
  42. data/lib/standard_flags/operations/restore_target.rb +197 -0
  43. data/lib/standard_flags/operations/rules.rb +233 -0
  44. data/lib/standard_flags/operations/validation.rb +154 -0
  45. data/lib/standard_flags/operations.rb +43 -0
  46. data/lib/standard_flags/parser.rb +16 -0
  47. data/lib/standard_flags/purge_job.rb +14 -0
  48. data/lib/standard_flags/registry.rb +38 -5
  49. data/lib/standard_flags/reporting.rb +51 -7
  50. data/lib/standard_flags/resolvers.rb +14 -7
  51. data/lib/standard_flags/result.rb +43 -0
  52. data/lib/standard_flags/rspec.rb +67 -13
  53. data/lib/standard_flags/runtime/active_record_store.rb +428 -0
  54. data/lib/standard_flags/runtime/cache.rb +98 -0
  55. data/lib/standard_flags/runtime/evaluation_tracker.rb +93 -0
  56. data/lib/standard_flags/runtime/memory_store.rb +408 -0
  57. data/lib/standard_flags/runtime/models.rb +43 -0
  58. data/lib/standard_flags/runtime/resolver.rb +256 -0
  59. data/lib/standard_flags/runtime/rule_snapshot.rb +60 -0
  60. data/lib/standard_flags/runtime/store.rb +161 -0
  61. data/lib/standard_flags/runtime/values.rb +181 -0
  62. data/lib/standard_flags/runtime.rb +266 -0
  63. data/lib/standard_flags/sensor.rb +12 -5
  64. data/lib/standard_flags/subscribers.rb +6 -0
  65. data/lib/standard_flags/testing.rb +100 -1
  66. data/lib/standard_flags/tooling/changes.rb +196 -0
  67. data/lib/standard_flags/tooling.rb +232 -19
  68. data/lib/standard_flags/version.rb +1 -1
  69. data/lib/standard_flags.rb +33 -5
  70. data/lib/tasks/standard_flags.rake +45 -1
  71. metadata +41 -1
data/README.md CHANGED
@@ -9,12 +9,15 @@ the [OpenFeature](https://openfeature.dev) shape (value, variant, reason,
9
9
  error code), so "why is this on?" is always a one-line answer.
10
10
 
11
11
  This is version 0.1.0 (Phase 1): registry, ENV layer and evaluation API. It
12
- needs no database tables. See [Roadmap](#roadmap).
12
+ needs no database tables. Unreleased on `main`: opt-in
13
+ [runtime rules](#runtime-rules) stored in the app's own database (the read
14
+ path; the audited write operations come next). See [Roadmap](#roadmap).
13
15
 
14
16
  - [Install](#install)
15
17
  - [Declaring flags](#declaring-flags)
16
18
  - [Reading flags](#reading-flags)
17
19
  - [How a value is decided](#how-a-value-is-decided)
20
+ - [Runtime rules](#runtime-rules)
18
21
  - [Environment variables](#environment-variables)
19
22
  - [Sensor rollouts](#sensor-rollouts)
20
23
  - [Controller and job guards](#controller-and-job-guards)
@@ -22,6 +25,7 @@ needs no database tables. See [Roadmap](#roadmap).
22
25
  - [Rake tasks](#rake-tasks)
23
26
  - [Observability](#observability)
24
27
  - [Health check and diagnostics](#health-check-and-diagnostics)
28
+ - [OpenFeature](#openfeature)
25
29
  - [Testing](#testing)
26
30
  - [Conformance suite](#conformance-suite)
27
31
  - [Bucketing](#bucketing)
@@ -56,6 +60,7 @@ StandardFlags.define do
56
60
  env_resolver -> { ENV.fetch("APP_ENVIRONMENT", Rails.env) }
57
61
 
58
62
  unit :account, from: ->(ctx) { ctx.account }
63
+ unit :phone, from: ->(ctx) { ctx.phone }, key: ->(phone) { phone.to_s.delete("^0-9+") }
59
64
 
60
65
  flag :new_checkout,
61
66
  owner: "payments",
@@ -94,8 +99,8 @@ end
94
99
  |------|--------|---------|---------|
95
100
  | `flag` | on / off | off | Temporary release flags: `remove_by:` and `final:` are required. With `permanent: true`, a standing switch instead (see below). |
96
101
  | `kill_switch` | on / off | on, fails open | Permanent switches that turn a feature off in an emergency. |
97
- | `mode` | declared values | first value | Staged rollouts. Presets: `:sensor` (off/sensor/on), `:cutover` (off/allowlist/all), `:shadow` (off/shadow/enforce); or `values:`. |
98
- | `experiment` | declared variants | first variant | Experiments. In 0.1.0 an experiment always resolves to its first variant (list `control` first) unless pinned by ENV. |
102
+ | `mode` | declared values | first value | Staged rollouts. Presets: `:sensor` (off/sensor/on), `:cutover` (off/allowlist/all), `:shadow` (off/shadow/enforce); or `values:`. May declare `remove_by:` with `final:`, or `permanent: true`. |
103
+ | `experiment` | declared variants | first variant | Experiments. Resolves to its first variant (list `control` first) unless pinned by ENV or split by a runtime rule's variant weights. |
99
104
  | `compat` | on / off | on | Compatibility shims that stay on until they are removed. |
100
105
  | `tombstone` | — | — | A removed key. It can never be declared again. |
101
106
 
@@ -108,23 +113,39 @@ end
108
113
  | `default:` | A value, or `{ env_name => value }`. Environments not listed get the kind's default. |
109
114
  | `env:` | Legacy environment variable name(s) still honoured. See [Environment variables](#environment-variables). |
110
115
  | `inverted:` | The legacy name is a `*_DISABLED` variable: legacy on means flag off. |
116
+ | `legacy_parser:` | `:strict` (default) or `:exact`: how legacy `env:` values are read. See [Exact legacy readers](#exact-legacy-readers). |
117
+ | `legacy_true:` | With `legacy_parser: :exact` on an on/off kind, the exact values that mean on. Default `%w[on]`. |
111
118
  | `forbidden_in:` | Environment name(s) where the flag is forced off. A pin that tries to turn it on is reported once per process. |
112
119
  | `fail:` | The value returned if evaluation raises. Kill switches default to on. |
113
120
  | `expose:` | `{ audience => wire_name }`, or a list of audiences to use the key. Default: not exposed. |
114
- | `unit:` | The unit the flag targets. Carried in the context now; used by targeting later. |
115
- | `remove_by:`, `final:` | On `flag`: the date it should be gone, and the value it settles on. |
116
- | `permanent:` | On `flag`: `true` for a standing switch with no `remove_by:`/`final:`. |
121
+ | `unit:` | The unit the flag targets. [Runtime rules](#runtime-rules) match members, cohorts and percentages on this unit's key. |
122
+ | `bucketing:` | On `flag`, `mode` and `experiment`: `{ version: 1 \| 2, salt: "..." }`, for a flag migrated from another system that must keep its old buckets. Needs `unit:`. |
123
+ | `remove_by:`, `final:` | On `flag` (required) and `mode` (optional, together): the date it should be gone, and the value it settles on. A mode's `final:` must be one of its values. |
124
+ | `permanent:` | On `flag` and `mode`: `true` for a standing switch with no `remove_by:`/`final:`. |
117
125
 
118
126
  The registry is validated when it loads. `StandardFlags::DefinitionError` is
119
127
  raised for a reused tombstoned key, a missing owner, a `flag` without
120
- `remove_by:`/`final:` (or a `permanent: true` flag with either), a default outside a mode's values, the same wire name
121
- used twice for one audience, an undeclared unit, or any unknown attribute.
128
+ `remove_by:`/`final:` (or a `permanent: true` flag or mode with either), a mode with only one of
129
+ `remove_by:`/`final:` or a `final:` outside its values, a `legacy_parser: :exact` without a legacy `env:`
130
+ name, a default outside a mode's values, the same wire name
131
+ used twice for one audience, an undeclared unit, a malformed `bucketing:` or
132
+ unit `key:`, or any unknown attribute.
133
+
134
+ ### Units
135
+
136
+ `unit :name, from: ->(ctx) { ... }` (or `resolver:`, any object with
137
+ `call(context)`) finds the unit's actor in a context. Runtime rules match a
138
+ unit by its **key**: `record.id.to_s` for anything with an `id`, otherwise
139
+ the value itself as a string; blank means missing. `key: ->(actor) { ... }`
140
+ normalises it in one place, such as a phone number to E.164. Pass actors by
141
+ unit name (`for: { account: account }`), or a target that answers the unit
142
+ name (`for: user` when `user.account` exists).
122
143
 
123
144
  ### Permanent flags
124
145
 
125
146
  Some switches are never meant to be removed: environment permissions such as
126
147
  demo pages, setup screens, or permission to send real messages outside
127
- production. Declare them as a `flag` with `permanent: true`:
148
+ production. Declare them as a `flag` (or a `mode`) with `permanent: true`:
128
149
 
129
150
  ```ruby
130
151
  flag :demo_pages, owner: "platform", permanent: true,
@@ -209,7 +230,10 @@ also carry an environment override and client attributes
209
230
  Evaluations are memoised per unit of work through the Rails executor, not
210
231
  Rack middleware, so requests, jobs, mailers and console reloads all get a
211
232
  consistent answer within one unit and a fresh read of ENV in the next.
212
- Outside an executor run nothing is memoised.
233
+ Outside an executor run nothing is memoised. With runtime rules on, the
234
+ flag's resolved unit key is part of the memo key, so unsaved records (a nil
235
+ `id`) and units whose `key:` reads something other than `id` never share an
236
+ answer.
213
237
 
214
238
  ## How a value is decided
215
239
 
@@ -217,13 +241,17 @@ Each evaluation walks these layers in order and stops at the first one that
217
241
  answers. Gates are never OR'd together.
218
242
 
219
243
  1. **Test override.** `with_flag(:x, true)`. Exists only in tests. Reason `STATIC`.
220
- 2. **Guard.** `forbidden_in:` forces the off value. Reason `DISABLED`.
244
+ 2. **Guard.** `forbidden_in:` forces the off value. Reason `DISABLED`. It
245
+ applies when either the context's `env` or the process's own environment
246
+ is forbidden, so a caller-supplied environment can't relax it.
221
247
  3. **ENV pin.** `STANDARD_FLAGS_<KEY>`, then legacy `env:` names. Reason
222
248
  `ENV_PIN`, or `KILL_SWITCH` when a kill switch is pinned off.
223
- 4. **Code default** for the current environment. Reason `DEFAULT`.
249
+ 4. **Runtime rule**, when [runtime rules](#runtime-rules) are on and the
250
+ flag's rule answers. Reasons `TARGETING_MATCH`, `SPLIT`, `STATIC` or
251
+ `KILL_SWITCH`, with a `rule_id`.
252
+ 5. **Code default** for the current environment. Reason `DEFAULT`.
224
253
 
225
- Runtime rules arrive between 3 and 4, so an ENV pin keeps beating any
226
- database rule and keeps working with the database down.
254
+ An ENV pin beats any database rule and keeps working with the database down.
227
255
 
228
256
  **Test overrides beat guards.** Layer 1 answers before layer 2, so
229
257
  `with_flag(:demo_pages, true)` turns a `forbidden_in: :production` flag on
@@ -231,19 +259,594 @@ even in production. That is what you want when testing the feature itself,
231
259
  but it means a spec cannot prove a guard with `with_flag`. Use a real ENV pin
232
260
  instead; see [Testing a guard](#testing-a-guard).
233
261
 
262
+ ## Runtime rules
263
+
264
+ Runtime rules change a flag without a redeploy, and let it differ per
265
+ account, organisation, phone or other unit. Each flag has at most one rule,
266
+ stored in the app's own database (Postgres). They are off by default: with
267
+ `config.runtime_rules` false, nothing reads a database, ActiveRecord is never
268
+ loaded by the gem, and every flag behaves exactly as in 0.1.0.
269
+
270
+ Rules change only through audited operations (see
271
+ [Changing flags](#changing-flags)), from the console, a rake task, or the
272
+ app's own admin and tools.
273
+
274
+ ### Turning them on
275
+
276
+ ```bash
277
+ bin/rails g standard_flags:migrations # existing installs
278
+ bin/rails g standard_flags:install --runtime # new installs: also writes the migration
279
+ bin/rails db:migrate
280
+ ```
281
+
282
+ ```ruby
283
+ # config/initializers/standard_flags.rb
284
+ StandardFlags.configure do |config|
285
+ config.runtime_rules = true
286
+ config.refresh_interval = 5 # seconds between revision checks
287
+ config.segment_resolver = ->(name, context) { Segments.member?(name, context.account) }
288
+ end
289
+ ```
290
+
291
+ Through the [OpenFeature provider](#openfeature), the segment resolver gets a
292
+ context whose actors are unit keys (strings), not records. If you use both,
293
+ handle both:
294
+
295
+ ```ruby
296
+ config.segment_resolver = lambda do |name, context|
297
+ account = context.account
298
+ account = Account.find_by(id: account) if account.is_a?(String) # an OpenFeature key
299
+ account.present? && Segments.member?(name, account)
300
+ end
301
+ ```
302
+
303
+ The migration creates four tables, with UUID keys when the app's generators
304
+ use them (`config.generators { |g| g.orm :active_record, primary_key_type: :uuid }`).
305
+ All four are new, so every index and constraint is created inside
306
+ `create_table` and StrongMigrations accepts it.
307
+
308
+ | Table | Holds |
309
+ |-------|-------|
310
+ | `standard_flags_rules` | One row per flag: `status` (draft, running, paused, stopped), `hash_version` and `salt`, `percentage_bps` (0–10,000), `rollout_value`, `variant_weights`, `fallthrough_value`, `stop_value`, `conditions` (platforms, version ranges, segments), attached `cohorts`, `member_count`. |
311
+ | `standard_flags_cohorts` | Named, reusable member lists of one unit, such as staff accounts. |
312
+ | `standard_flags_memberships` | A unit key in exactly one rule or cohort, with the value it serves and an optional `expires_at`. Removed rows keep `removed_at`. |
313
+ | `standard_flags_state` | One row; `revision` moves on every change, to the next value of its own sequence, so a number taken by a write that rolled back is never reused. A database built from `schema.rb` or `structure.sql` has the table but not the row (the migration inserts it); the first change creates it, until then every revision check reloads the rules, and the health check warns. |
314
+
315
+ Stored values are strings: `on`/`off` for on/off kinds, a mode value, or a
316
+ variant. The models live in `lib/` (never `app/models`) and have no
317
+ associations. Unit keys can be phone numbers or emails, so they are kept out
318
+ of logs and consoles; see [Privacy](#privacy).
319
+
320
+ ### How a rule decides
321
+
322
+ The rule's status decides first:
323
+
324
+ | Status | Serves |
325
+ |--------|--------|
326
+ | `draft` | Nothing: the code default. |
327
+ | `paused` | The code default. Its settings are kept, so it can resume. |
328
+ | `stopped` | `stop_value` to everyone. Reason `STATIC`, rule `stopped`. |
329
+ | `running` | The first of the steps below that answers. |
330
+
331
+ 1. **Direct members** of this unit. A member serving the flag's off value
332
+ (a deny) wins over any other. `TARGETING_MATCH`, rule `deny` or `allow`.
333
+ 2. **Attached cohorts** the unit belongs to. A cohort serving the off value
334
+ wins; otherwise the first match in declared order. Rule `cohort:<key>`.
335
+ 3. **Segments**, each asked of `config.segment_resolver.call(name,
336
+ context)` in order. Skipped when no resolver is set. Rule `segment:<name>`.
337
+ 4. **Client conditions**: `platforms` and `versions` (`{ "android" =>
338
+ ">= 1.4.0" }`, compared with `Gem::Requirement` against
339
+ `context.client[:platform]` and `[:version]`). When they aren't met, the
340
+ rule skips straight to the fallthrough.
341
+ 5. **Percentage and variants.** A unit whose rollout bucket is below
342
+ `percentage_bps` gets `rollout_value` (on/off kinds default to `on`), reason
343
+ `SPLIT`, rule `percentage`. With `variant_weights` (summing to 10,000),
344
+ units inside the percentage, or every unit when there is no percentage,
345
+ get a variant by a separate variant bucket, rule `variants`. Hash version
346
+ 1 uses `Bucket.v1(salt, key)` for both decisions; version 2 uses
347
+ `Bucket.v2("rollout" | "variant", salt, key)`.
348
+ 6. **Fallthrough**: `fallthrough_value` if set (`TARGETING_MATCH`, rule
349
+ `fallthrough`), otherwise the code default.
350
+
351
+ A kill switch served `false` from a rule reads as `KILL_SWITCH`, so throwing
352
+ one from the database looks the same as pinning it off.
353
+
354
+ When a rule needs the unit (it has members, cohorts, segments, a percentage
355
+ or weights) and the context has no key for the flag's unit, the result is
356
+ the fallthrough or the code default with reason `ERROR` and error code
357
+ `TARGETING_KEY_MISSING`. That emits `targeting_key_missing.standard_flags`
358
+ but reports nothing, because reads with no unit are often legitimate. A
359
+ stored value the flag can't take (an unknown mode value, weights that don't
360
+ sum, a bad version range) fails only that flag: its `fail:` value with
361
+ `PARSE_ERROR`, reported once through the error reporter.
362
+
363
+ ### What a read costs
364
+
365
+ * **Rules** are cached per process in an immutable snapshot: every rule,
366
+ plus each cohort's key, unit and member count, never its members. On an
367
+ evaluation, once `refresh_interval` has passed, one query reads
368
+ `standard_flags_state.revision`, and the rules reload only when it moved.
369
+ No background thread is started, so it is safe under forking servers.
370
+ * **Memberships** cost one indexed query per unit key per unit of work: it
371
+ returns that unit's live memberships across every rule and cohort, and is
372
+ memoised through the executor. Twenty flags checked for one account in a
373
+ request cost one query. It is skipped entirely when the flag's rule has no
374
+ members and no attached cohort with members.
375
+ * **Lists** load in one query with `StandardFlags.preload`, so a loop
376
+ doesn't run a query per record:
377
+
378
+ ```ruby
379
+ StandardFlags.preload(:account, accounts)
380
+ accounts.each { |account| notify(account) if StandardFlags.on?(:new_checkout, for: { account: account }) }
381
+ ```
382
+
383
+ * **One revision per unit of work.** The first evaluation in a request or
384
+ job pins the rules snapshot, and every later evaluation in that run reuses
385
+ it, so a page, a client payload or a loop never mixes two revisions.
386
+ Outside an executor run each evaluation reads the process cache.
387
+
388
+ The spec suite asserts each of these query counts against Postgres.
389
+
390
+ ### When the database is unavailable
391
+
392
+ The process keeps serving the last good snapshot, marks it stale, reports the
393
+ error once and emits `runtime_stale.standard_flags`; it tries again one
394
+ interval later. A process that has never loaded rules serves code defaults.
395
+ Inside a host transaction every read runs in a savepoint, so a failed read
396
+ can't abort the host's transaction. The read path never raises.
397
+
398
+ When a unit's membership lookup fails, the failure is reported once and
399
+ remembered for the rest of the unit of work, so an outage costs one failed
400
+ query per unit per request, not one per flag. Flags that needed it skip the
401
+ direct-member and cohort steps and carry on through segments, the split and
402
+ the fallthrough (or the code default), with reason `ERROR`, error code
403
+ `GENERAL` and the deciding step's `rule_id`. `StandardFlags.preload` never
404
+ raises either: on a store error, or a unit `key:` that raises, it reports
405
+ once (by error class, never a unit key) and returns 0, and each evaluation
406
+ then reads on its own.
407
+
408
+ A stored row whose shape no rule can have (`conditions` that isn't an
409
+ object, a cohort attachment that isn't an object, and so on) fails only its
410
+ flag, with `PARSE_ERROR` and `rule_invalid.standard_flags`, like an
411
+ unservable value.
412
+
413
+ ### Without a database
414
+
415
+ `config.runtime_store` takes any `StandardFlags::Runtime::Store`. The
416
+ in-memory `MemoryStore` serves specs and apps without a database:
417
+
418
+ ```ruby
419
+ store = StandardFlags::Runtime::MemoryStore.new
420
+ store.put_rule(:new_checkout, status: :running, percentage_bps: 500)
421
+ store.put_cohort(:staff, unit: :account)
422
+ store.add_member(cohort: :staff, unit: :account, unit_key: "42", value: true)
423
+ store.put_rule(:new_checkout, cohorts: { staff: true })
424
+ StandardFlags.configure { |c| c.runtime_rules = true; c.runtime_store = store }
425
+ ```
426
+
427
+ ### Privacy
428
+
429
+ Unit keys are stored raw, because writes and lookups need the real value.
430
+ The gem keeps them out of the places it controls:
431
+
432
+ * `Membership` values hide `unit_key` from `inspect`, `to_s` and `pp` (the
433
+ console's inspector). `to_h` still includes it.
434
+ * When runtime rules are on, the engine adds `unit_key` to
435
+ `ActiveRecord::Base.filter_attributes`, which is what ActiveRecord's SQL
436
+ log filters bind values through; a model's own filter doesn't reach the
437
+ log. The setting is global, so any other model's `unit_key` column is
438
+ filtered too; the name is deliberately narrow.
439
+ * Membership read errors are reported by error class only, without the
440
+ driver's message or cause, which can quote the value.
441
+ * Memberships are inserted with every value bound, never written into the
442
+ SQL text, and lookups, updates and purge bind unit keys too.
443
+
444
+ That filter can't help when the connection has **prepared statements off**
445
+ (`prepared_statements: false`, common behind a transaction-mode connection
446
+ pooler): values are then inlined into the SQL text, which reaches SQL logs,
447
+ `sql.active_record` payloads and APM span descriptions as written. The
448
+ health check warns in that case. Either keep prepared statements on for the
449
+ connection, or make sure those sinks scrub SQL text.
450
+
451
+ ### Migrated flags
452
+
453
+ A flag moved from another system declares `bucketing: { version: 1, salt:
454
+ "old_key" }` so its units keep their buckets; the rule copies those values
455
+ when it is first written, and its salt never changes afterwards.
456
+
457
+ ## Changing flags
458
+
459
+ Every change to a rule, cohort or membership goes through an operation in
460
+ `StandardFlags::Operations`. Each one is called as
461
+ `.call(key_or_cohort, actor:, reason:, expected_revision: nil, **args)` and
462
+ returns a `StandardFlags::Result` (`success?`, `value`, `errors`, plus a
463
+ `code` Symbol on failure). It never raises for a refusal.
464
+
465
+ ```ruby
466
+ ops = StandardFlags::Operations
467
+ ops::Ramp.call(:new_checkout, bps: 500, actor: current_user, reason: "5% canary")
468
+ ops::SetValue.call(:strict_gates, value: :sensor, actor: current_user, reason: "observe before enforcing")
469
+ ops::SetValue.call(:ai_assistant, value: false, actor: current_user, reason: "provider outage") # kill switch
470
+ ops::Start.call(:new_checkout, actor: current_user, reason: "go")
471
+
472
+ ops::CreateCohort.call("staff", unit: :account, name: "Staff", actor: current_user, reason: "dogfood")
473
+ ops::AddMembers.call("cohort:staff", keys: staff_accounts, actor: current_user, reason: "dogfood")
474
+ ops::AttachCohort.call(:new_checkout, cohort: "staff", value: true, actor: current_user, reason: "dogfood")
475
+
476
+ result = ops::Pause.call(:new_checkout, actor: current_user, reason: "error spike", expected_revision: 7)
477
+ result.code # => :stale_revision if someone changed the rule since you read revision 7
478
+ ```
479
+
480
+ A successful Result's `value` has the key (or `cohort:`), the state after
481
+ the change (`rule:` or `state:`), `revision:` and `store_revision:`, plus
482
+ what the operation changed. `revision` is the number `expected_revision` is
483
+ checked against, so it can be passed straight back: a rule's `lock_version`,
484
+ or for cohort operations the store's revision. `store_revision` is always
485
+ `standard_flags_state.revision`.
486
+
487
+ | Operation | Scope | Does |
488
+ |-----------|-------|------|
489
+ | `Start` | `flags:write` | Draft or paused → running, after checking everything the rule would serve. |
490
+ | `Pause` | `flags:write` | Running → paused. A paused rule serves the code default and keeps its settings, so `Start` resumes it. |
491
+ | `Stop(serve:)` | `flags:write` | → stopped, serving `serve:` to everyone (the winner, or the flag's `final:`) until the code drops the flag. |
492
+ | `Ramp(bps:, value: nil)` | `flags:ramp` | Sets the percentage (0–10,000 basis points) and, for modes and experiments, the value it serves. At 10,000 it records `full_since`. |
493
+ | `SetVariants(weights:)` | `flags:ramp` | Weights over the flag's variants or mode values, summing to 10,000. `{}` clears them. |
494
+ | `SetValue(value:)` | `flags:write` | The fallthrough value, served to every unit nothing else matched. Moves a mode off → sensor → on and throws a kill switch. `nil` clears it. |
495
+ | `SetConditions(platforms:, versions:, segments:)` | `flags:write` | Replaces the conditions; omitted ones are cleared. |
496
+ | `AddMembers(keys:, value:, unit:, expires_at:)` | `flags:write` | Adds units (records or keys) to a rule or a cohort. Adding an existing member with a new value or expiry keeps the old row as removed and adds a new one, so [Restore](#restore) can read it back; adding it unchanged writes nothing. |
497
+ | `RemoveMembers(keys:, unit:)` | `flags:write` | Removes them (soft delete, see retention below). |
498
+ | `CreateCohort(unit:, name:, description:)` / `ArchiveCohort` | `flags:write` | Named member lists of one unit. Archiving needs the cohort detached everywhere. |
499
+ | `AttachCohort(cohort:, value:)` / `DetachCohort(cohort:)` | `flags:write` | Attach a cohort to a flag, serving `value:` to its members. |
500
+
501
+ A target is a flag key, or a cohort as `"cohort:staff"` (or
502
+ `StandardFlags::Operations.cohort(:staff)`). Values are Ruby values or their
503
+ stored strings (`true` or `"on"`, `:sensor` or `"sensor"`). Member keys go
504
+ through the unit's `key:`, so records, raw keys and unnormalised phone
505
+ numbers all work.
506
+
507
+ ### What every operation does
508
+
509
+ 1. **Actor.** `actor:`, else `config.actor_resolver` (by default `Current.user`
510
+ when the app defines `Current`). With neither, it fails
511
+ (`:actor_missing`). Work no person does passes
512
+ `StandardFlags::Actor.system("name")`.
513
+ 2. **Policy.** `config.authorize = ->(actor, scope, key) { ... }` must return
514
+ truthy. Scopes are `flags:read`, `flags:write` and `flags:ramp` (ramping
515
+ is granted separately, so on-call can ramp without changing targeting).
516
+ The key is the flag key Symbol, or `"cohort:<key>"`; `AttachCohort` and
517
+ `DetachCohort` ask about both the flag and the cohort. The default allows
518
+ system actors and nobody else, so wire it to your policy layer:
519
+ ```ruby
520
+ config.authorize = lambda do |actor, scope, _key|
521
+ next true if actor.is_a?(StandardFlags::Actor) # rake tasks
522
+ scope == "flags:ramp" ? actor.on_call? || actor.admin? : actor.admin?
523
+ end
524
+ ```
525
+ 3. **Refusals.** Unknown (`:unknown_flag`) and tombstoned (`:tombstoned_flag`)
526
+ keys, and flags an ENV pin decides (`:pinned_by_env`; the message names
527
+ the variable, never its value). An ENV pin always beats the database, so
528
+ writing under one would change nothing anyone sees.
529
+ 4. **One transaction.** The rule is created on first use (salt and hash
530
+ version from `bucketing:`, else a random salt and v2) and locked `FOR
531
+ UPDATE`, then the cohorts it needs, by id; `expected_revision` is checked
532
+ against its `lock_version` (`:stale_revision`; for cohort operations,
533
+ against the store's revision); the change is validated and saved. A rule
534
+ that is running afterwards is checked whole, as `Start` checks it, so no
535
+ edit can leave one the read path would refuse. Then
536
+ `standard_flags_state.revision` moves on. Inside the app's own
537
+ transaction it runs in a savepoint and commits with it.
538
+ 5. **Audit**, in the same transaction, in its own savepoint (below).
539
+ 6. **After the commit**, never while the write's locks are held: the
540
+ process cache is expired (so this process sees the change at once), the
541
+ unit of work's memo is cleared, and the events go out. Inside the app's
542
+ transaction that happens when it commits, and not at all if it rolls
543
+ back.
544
+
545
+ Locks are always taken in one order: the rule or cohort being changed, then
546
+ cohorts by id, then memberships, then the state row; purge locks the rules
547
+ and cohorts it recounts first. So two operations, or an operation and purge,
548
+ never wait on each other.
549
+
550
+ Failures carry a `code`: `:actor_missing`, `:unauthorized`, `:invalid`,
551
+ `:limit_exceeded`, `:unknown_flag`, `:tombstoned_flag`, `:pinned_by_env`,
552
+ `:stale_revision`, `:already_exists` (`CreateCohort` on a taken key),
553
+ `:runtime_rules_off`, `:audit_failed`, `:store_error` (reported) or `:error`
554
+ (unexpected, reported). A success means the change committed (or, inside the
555
+ app's transaction, commits with it): a write whose transaction a swallowed
556
+ error aborted fails with `:store_error` instead of reporting a change that
557
+ Postgres silently rolled back.
558
+
559
+ ### Validation and limits
560
+
561
+ Everything is checked on write and nothing on read (R13): values must be
562
+ ones the flag can take, weights must use its variants or mode values and sum
563
+ to 10,000, `bps` must be 0–10,000, percentages, variants, segments and
564
+ members need the flag to declare a `unit:`, version ranges must parse, and a
565
+ cohort's unit must match the flag's. Limits, each configurable:
566
+
567
+ ```ruby
568
+ config.max_members = 10_000 # live members per rule or cohort
569
+ config.max_keys_per_operation = 1_000
570
+ config.max_cohorts_per_rule = 20
571
+ config.max_conditions_bytes = 64 * 1024
572
+ ```
573
+
574
+ ### Audit
575
+
576
+ Every operation records the actor, the reason and the full rule (or cohort)
577
+ state before and after, without members, and publishes one event:
578
+
579
+ | Event | Operation |
580
+ |-------|-----------|
581
+ | `standard_flags.flag.started` / `.paused` / `.stopped` | Start, Pause, Stop |
582
+ | `standard_flags.flag.ramped` / `.variants_set` / `.value_set` / `.conditions_set` | Ramp, SetVariants, SetValue, SetConditions |
583
+ | `standard_flags.flag.members_added` / `.members_removed` | AddMembers, RemoveMembers on a rule |
584
+ | `standard_flags.cohort.created` / `.archived` / `.attached` / `.detached` | the cohort operations |
585
+ | `standard_flags.cohort.members_added` / `.members_removed` | AddMembers, RemoveMembers on a cohort |
586
+ | `standard_flags.flag.restored` / `standard_flags.cohort.restored` | [Restore](#restore): one row per flag or cohort put back, member changes as counts |
587
+ | `standard_flags.members.revealed` | Not a change: an operator revealed members' unit keys ([Operator tools](#operator-tools-mcp)). Counts only. |
588
+ | `standard_flags.flag.probed` | Not a change: an operator evaluated a flag for one unit key, which says whether it is a member ([Operator tools](#operator-tools-mcp)). Counts only. |
589
+
590
+ The payload has `actor` (the record, or nil for a system actor),
591
+ `actor_label`, `reason`, `key` or `cohort`, `revision` and `store_revision`
592
+ (as in the Result), `before` and `after`.
593
+ Membership changes add `unit`, `value` and counts (`requested`, `added`,
594
+ `updated`, `removed`). **Unit keys never appear** in an audit row, a
595
+ notification, a Result or an error report: they can be phone numbers or
596
+ emails.
597
+
598
+ With [standard_audit](https://github.com/rarebit-one/standard_audit) loaded,
599
+ each change writes one audit row inside the operation's transaction, in its
600
+ own savepoint. Either subscribe standard_audit to the events:
601
+
602
+ ```ruby
603
+ StandardAudit.configure do |config|
604
+ StandardFlags::Events.auditable.each { |pattern| config.subscribe_to(pattern) }
605
+ end
606
+ ```
607
+
608
+ or don't, and the gem writes the row itself through
609
+ `StandardAudit::Operation#audit!` (as `StandardFlags::Operations::AuditWriter`).
610
+ It checks which: there is one row either way. If your app keeps an
611
+ `AuditCatalogue::ACTIONS`, add `StandardFlags::Events.auditable` to it, or
612
+ standard_audit's declaration check fails in development and test.
613
+
614
+ standard_audit swallows a failed write by default, and on Postgres a failed
615
+ statement aborts the whole transaction; the savepoint confines the failure
616
+ to the audit row. With `raise_on_audit_write_error`, a failed audit write
617
+ fails the operation (`:audit_failed`) and rolls it back, on either path.
618
+ Without it the change commits without its row and the gem reports the loss,
619
+ as standard_audit's default does. (A failure standard_audit's subscriber
620
+ swallows before it reaches the database can't be seen from outside; it
621
+ reports those itself.)
622
+
623
+ When standard_audit's subscriber writes the row, the event is published
624
+ inside the transaction, so any other subscriber to it runs there too. In
625
+ every other case the events are published after the commit. Without
626
+ standard_audit, operations only publish the events. `change.standard_flags`
627
+ carries a one-line summary for the gem's own subscribers (the Logger line
628
+ and `config.add_notifier`), always after the commit.
629
+
630
+ ### Rake tasks for break-glass changes
631
+
632
+ For a console with no admin UI. Each task needs `REASON=` (written to the
633
+ audit log), runs as `StandardFlags::Actor.system("rake")`, prints the outcome
634
+ and the new revision, and refuses pinned flags with the variable's name.
635
+
636
+ ```bash
637
+ bin/rails flags:show KEY=new_checkout # declaration, value, pin, stored rule
638
+ bin/rails flags:show KEY=cohort:staff
639
+ bin/rails flags:set KEY=strict_gates VALUE=sensor REASON="observe first"
640
+ bin/rails flags:ramp KEY=new_checkout BPS=500 REASON="5% canary"
641
+ bin/rails flags:start KEY=new_checkout REASON="go"
642
+ bin/rails flags:pause KEY=new_checkout REASON="error spike"
643
+ bin/rails flags:stop KEY=new_checkout SERVE=on REASON="winner"
644
+ bin/rails flags:members:add KEY=new_checkout KEYS=42,43 VALUE=on [EXPIRES_AT=2026-12-01T00:00:00Z] REASON="pilot"
645
+ bin/rails flags:members:remove KEY=cohort:staff KEYS=42 REASON="left"
646
+ bin/rails flags:purge REASON="weekly"
647
+ bin/rails flags:restore AT=2026-11-20T09:00:00Z [KEYS=new_checkout,cohort:staff] [APPLY=1] REASON="bad ramp"
648
+ ```
649
+
650
+ The default `config.authorize` allows system actors; if you replace it, keep
651
+ allowing them or the rake tasks are refused too.
652
+
653
+ ### Retention
654
+
655
+ `RemoveMembers` keeps the row with `removed_at` (and a changed membership
656
+ keeps its old row the same way), so [Restore](#restore) can put members
657
+ back. `bin/rails flags:purge` (or `StandardFlags::PurgeJob`,
658
+ an ActiveJob, defined when the app loads ActiveJob) hard-deletes memberships
659
+ removed or expired more than `config.membership_retention` ago (default 90
660
+ days). Schedule the job, for example daily.
661
+
662
+ ### Stale rules
663
+
664
+ `flags:stale` also lists rules at 100% or stopped for 30 days or more, rules
665
+ not evaluated in 14 days, rules for undeclared or tombstoned keys, and
666
+ memberships past retention. "Not evaluated" comes from `last_evaluated_at`:
667
+ each process notes in memory which flags it evaluated. Nothing is written
668
+ during an evaluation. When a unit of work ends (the Rails executor's
669
+ `complete` hook, after the request or job has done its work), the gem writes
670
+ the noted flags if it hasn't in the last `config.evaluation_tracking_interval`
671
+ (default an hour), so at most once per interval per process, in one
672
+ `UPDATE`. That `UPDATE` never waits: it skips rows a write holds (`FOR
673
+ UPDATE SKIP LOCKED`), it is skipped inside an open transaction, and it
674
+ changes neither `lock_version` nor `updated_at`. A process that evaluates
675
+ flags outside the executor never writes them. A failed write is reported
676
+ once and retried, and `config.track_evaluations = false` turns it off (and
677
+ the 14-day check with it). Operator reads (the MCP tools and the admin page)
678
+ evaluate flags without noting them, so looking at a dead flag doesn't hide
679
+ it.
680
+
681
+ ### Restore
682
+
683
+ `StandardFlags::Operations::Restore` (and `bin/rails flags:restore`) puts
684
+ rules and memberships back as they were at a past time T:
685
+
686
+ ```ruby
687
+ restore = StandardFlags::Operations::Restore
688
+ restore.call(at: Time.utc(2026, 11, 20, 9), reason: "bad ramp") # dry run
689
+ restore.call(at: Time.utc(2026, 11, 20, 9), keys: %w[new_checkout cohort:staff], apply: true, reason: "bad ramp")
690
+ ```
691
+
692
+ - **A rule's state at T** is the after-state of its latest audit row at or
693
+ before T, read back through standard_audit's query API
694
+ (`StandardAudit::AuditLog`, the `audit_logs` table). Without standard_audit
695
+ it fails with `:audit_unavailable`. Only an audited state drives a change:
696
+ a flag with no row at or before T is skipped ("no audit history at T; left
697
+ unchanged"), never read as "no rule then". Rows go missing for ordinary
698
+ reasons (the audit log's retention, auditing set up after the rule, a
699
+ write standard_audit swallowed), and a long-thrown kill switch is exactly
700
+ the rule nobody touches.
701
+ - **Members at T** come from the memberships table: rows created by T and
702
+ not removed or expired then. Removed and changed rows are kept for
703
+ `config.membership_retention`, so a T older than that is refused
704
+ (`:retention_exceeded`). Members whose expiry has passed since T are not
705
+ restored (the note says how many).
706
+ - **Dry run by default.** The Result lists each flag (and each cohort, for
707
+ its members) as `unchanged`, `planned` or `skipped`, with the changes as
708
+ text, member changes as counts.
709
+ - **`apply: true`** (`APPLY=1`) writes each flag's state at T (its
710
+ settings, attached cohorts in their old order, and direct members) and
711
+ each cohort's members as one store write: one revision bump, one
712
+ `standard_flags.flag.restored` or `standard_flags.cohort.restored` row
713
+ (the full state before and after, member changes as counts), as
714
+ `StandardFlags::Actor.system("restore")` with the reason
715
+ `"restore to <T>: <reason>"`. Evaluators see the state before or the state
716
+ after, never a mix of the two, and a write that fails changes nothing.
717
+ Inside it, members are removed before any are added, so
718
+ `config.max_members` counts the end state. Cohorts go first, so a flag
719
+ that attaches one serves its members as they were. Stored unit keys are
720
+ put back as they are, not passed through the unit's `key:` again. A
721
+ flag's write expects the revision it was planned at, so a change made
722
+ meanwhile stops that flag (`:stale_revision`) rather than being
723
+ overwritten. Targets are independent: when some fail the Result is a
724
+ failure (`:partial_failure`) whose `value` still lists what was applied,
725
+ what failed and why.
726
+ - **Skipped**, with a note: ENV-pinned flags, undeclared or tombstoned
727
+ keys, flags with no audit history at T, and what the operations don't do
728
+ (un-stop a rule, clear a percentage, change a rule's salt).
729
+ - **`AT=`** must name its zone (`2026-11-20T09:00:00Z` or `+08:00`); a bare
730
+ local time is refused rather than read in the server's zone.
731
+
732
+ Restore authorises as the system actor, so it is a console and rake tool,
733
+ not an MCP tool or an admin button.
734
+
735
+ ## Operator tools (MCP)
736
+
737
+ `StandardFlags::MCP` has one class per tool for an agent or chat surface,
738
+ with no dependency on any MCP framework. Each instance has `name`,
739
+ `description`, `input_schema` (a JSON Schema Hash) and
740
+ `call(arguments, actor:)`, which returns a JSON-safe Hash with String keys,
741
+ or `{ "error" => { "code" =>, "message" => } }`. Adapting them to a tool
742
+ registry takes a few lines:
743
+
744
+ ```ruby
745
+ StandardFlags::MCP.tools.each do |tool|
746
+ server.register_tool(name: tool.name, description: tool.description, input_schema: tool.input_schema) do |arguments, context|
747
+ tool.call(arguments, actor: context.user)
748
+ end
749
+ end
750
+ ```
751
+
752
+ | Tool | Scope | Does |
753
+ |------|-------|------|
754
+ | `list_flags` | `flags:read` (per flag) | Every flag the actor may read: kind, owner, values, value with no unit, source, ENV pin, rule summary. |
755
+ | `get_flag` | `flags:read`; with `unit_key`, `flags:write` and `reason` | One flag: value, reason, `rule_id` and source (`env_pin`, `runtime_rule`, `guard`, `code_default`, `error`, `test_override`), the ENV pin and the stored rule in full. With `unit_key` (normalised through the unit's `key:`, masked in the answer) it evaluates for that unit, which is a reveal (below). |
756
+ | `start_flag`, `pause_flag`, `stop_flag`, `ramp_flag`, `set_flag_value` | as the operation | Run Start, Pause, Stop, Ramp and SetValue. |
757
+ | `list_members` | `flags:read` | One page (`offset`, `limit` up to 200) of a flag's (`key`) or a cohort's (`cohort`) members. |
758
+ | `add_members`, `remove_members` | `flags:write` | Run AddMembers and RemoveMembers on a flag or a cohort. |
759
+ | `list_cohorts`, `get_cohort` | `flags:read` (per cohort) | Cohorts with their unit, member count, archived state and the flags they're attached to. |
760
+
761
+ - **Reads** ask `config.authorize` for `"flags:read"`; `list_flags` and
762
+ `list_cohorts` list only what the actor may read, and so do the
763
+ cross-references: a cohort's `attached_to` names only flags the actor may
764
+ read (`hidden_flags` counts the rest), and a flag's `rule.cohorts` only
765
+ cohorts it may read (`cohort:<key>`; `hidden_cohorts` counts the rest).
766
+ Reads never mark a rule as evaluated. **Writes** go through
767
+ the operations, need `reason` and accept `expected_revision` (the rule's
768
+ `revision` from `get_flag`). A failed operation's code is the error code:
769
+ `pinned_by_env`, `stale_revision`, `unauthorized`, `invalid` and so on.
770
+ - **Pins** show as `{ "env_var" => "STANDARD_FLAGS_X", "label" => "Pinned by environment (STANDARD_FLAGS_X)" }`,
771
+ never the variable's value.
772
+ - **Unit keys are masked** (`•••4567`: the last four characters, fewer for
773
+ short keys so at least half stays hidden). `list_members` shows them in
774
+ full only with `reveal: true` and a `reason`, for an actor allowed
775
+ `"flags:write"` on the target. A reveal publishes (and with standard_audit,
776
+ records) `standard_flags.members.revealed` with the actor, reason, flag or
777
+ cohort and counts, never the keys. `get_flag` with `unit_key` says
778
+ whether that unit is a member (and the mask gives away its last four), so
779
+ it is a reveal too: `"flags:write"` on the flag, a `reason`, and a
780
+ `standard_flags.flag.probed` row with counts and no key.
781
+ - **Reveals fail closed** when standard_audit's
782
+ `raise_on_audit_write_error` is set: keys (or a probe's answer) come back
783
+ only once the row is known to be written. The row is written in a store
784
+ transaction savepoint, so a failure standard_audit's subscriber swallows
785
+ still aborts it, and is read back by a one-off `audit_ref`. With
786
+ standard_audit's `config.async` the row can't be confirmed, so the read is
787
+ refused. Without `raise_on_audit_write_error`, a lost row is reported and
788
+ the read goes ahead, as for writes.
789
+ - **One instance per tool is safe to share** across threads and actors (as
790
+ an MCP server registers them): it is frozen, and each call runs on its
791
+ own copy holding that call's actor, arguments and store read.
792
+ - A missing `actor:` falls back to `config.actor_resolver`. The generated
793
+ admin page never relies on that (below).
794
+
795
+ ## Admin page
796
+
797
+ ```bash
798
+ bin/rails g standard_flags:admin [--path=/admin/flags] [--base-controller=ApplicationController] \
799
+ [--controller=Admin::FlagsController] [--pages-path=app/javascript/pages] [--actor-method=current_user]
800
+ bin/rails standard_flags:typescript
801
+ ```
802
+
803
+ It writes code your app owns and restyles:
804
+
805
+ - **A controller** inheriting from `--base-controller` (where your admin
806
+ authentication lives), with `index`, `show` and one action per operation
807
+ (`start`, `pause`, `stop`, `ramp`, `set_value`, `add_members`,
808
+ `remove_members`). Every request runs as the signed-in user, from
809
+ `--actor-method` (default `current_user`); when that is nil it answers 401
810
+ (`standard_flags_deny`, yours to change to a redirect) before any tool
811
+ runs, and never falls back to `config.actor_resolver`, which may return a
812
+ system actor for jobs. Pages read through the MCP tools, so
813
+ `config.authorize` decides who sees what and members stay masked. Each
814
+ action calls its operation with the form's reason and the revision the
815
+ page showed, then redirects back with a flash.
816
+ - **Unit keys are posted as `unit_keys`**, which Rails' default
817
+ `config.filter_parameters` (`_key`) keeps out of the request log and error
818
+ trackers. If your app's list doesn't match it, add `:unit_keys`. An MCP
819
+ host should likewise not log `get_flag`'s `unit_key` or the member tools'
820
+ `keys` arguments.
821
+ - **Routes** under `--path`: `GET /`, `GET /:id`, `POST /:id/<operation>`,
822
+ named `standard_flags_flags`, `standard_flags_flag` and
823
+ `standard_flags_<operation>_flag`.
824
+ - **Two Inertia pages**, `standard_flags/index.tsx` and `show.tsx`, in plain
825
+ semantic markup with no styling framework, typed from the
826
+ `standard_flags:typescript` output (`FlagList`, `FlagDetail`,
827
+ `FlagMemberPage`, `FlagAuditEntry`). The show page has the rule, the
828
+ members (masked, paged), recent audit entries when standard_audit is
829
+ loaded, and a form per operation. A pinned flag is read-only, labelled
830
+ "Pinned by environment (VAR)".
831
+
832
+ The gem never reads these files back: move the routes, cut operations, or
833
+ restyle the pages freely.
834
+
234
835
  ## Environment variables
235
836
 
236
837
  Every flag can be pinned with its canonical variable, `STANDARD_FLAGS_<KEY>`
237
838
  (the key upcased): `STANDARD_FLAGS_NEW_CHECKOUT=on`.
238
839
 
239
- One strict parser reads every value, trimmed and case-insensitive:
840
+ One strict parser reads every value, trimmed and case-insensitive (a flag
841
+ may opt its legacy names into [exact reading](#exact-legacy-readers)):
240
842
 
241
843
  - on/off kinds: `on`/`off`, `true`/`false`, `1`/`0`, `yes`/`no`;
242
844
  - modes: a declared value; experiments: a declared variant.
243
845
 
244
846
  Anything else is ignored and reported once per process per variable, through
245
847
  `Rails.error.report(handled: true)` and a `pin_rejected.standard_flags`
246
- notification. A blank value counts as unset.
848
+ notification. A blank value counts as unset (except under
849
+ [exact reading](#exact-legacy-readers), where a blank legacy on/off value pins off).
247
850
 
248
851
  ### Legacy names
249
852
 
@@ -266,6 +869,37 @@ strict parser doesn't accept are ignored. A legacy `ENV["X_DISABLED"].present?`
266
869
  check treated `X_DISABLED=false` as disabled; with `inverted: true` it now
267
870
  means enabled. Call that out when migrating a flag.
268
871
 
872
+ ### Exact legacy readers
873
+
874
+ Some legacy readers were exact, `ENV["X"] == "on"`, and code that destroys
875
+ data may rely on that: `X=true` or `X=ON` never turned it on. To keep an
876
+ exact reader's meaning, declare `legacy_parser: :exact`:
877
+
878
+ ```ruby
879
+ flag :purge_inactive, owner: "platform", permanent: true,
880
+ env: "ACME_PURGE_INACTIVE", legacy_parser: :exact
881
+ flag :bulk_export, owner: "reporting", permanent: true,
882
+ env: "ACME_BULK_EXPORT", legacy_parser: :exact, legacy_true: %w[on enabled]
883
+ mode :strict_gates, owner: "platform", preset: :sensor,
884
+ env: "ACME_STRICT_GATES", legacy_parser: :exact
885
+ ```
886
+
887
+ - It applies to legacy `env:` names only. The canonical
888
+ `STANDARD_FLAGS_<KEY>` pin is always read by the strict parser.
889
+ - On/off kinds: a value in `legacy_true:` (default `%w[on]`) means on; any
890
+ other non-blank value pins off, as the old reader did, and is never
891
+ reported as rejected. `inverted: true` still flips the result.
892
+ - Modes and experiments: a value matches only if it equals a declared value
893
+ exactly (case-sensitive, no trimming); anything else is rejected and
894
+ reported like any unparseable pin.
895
+ - Matching does no trimming or case folding.
896
+ - A legacy variable that is set but blank (`X=""`, `X=" "`) pins an on/off
897
+ flag off, as `ENV["X"] == "on"` did, so blanking the variable disarms the
898
+ flag even when a runtime rule or default would serve on. Only an unset
899
+ variable falls through. Two exceptions keep blank as unset: an `inverted:`
900
+ name (pinning it would turn the flag on) and modes and experiments, where
901
+ no value is "off". The canonical pin always treats blank as unset.
902
+
269
903
  ## Sensor rollouts
270
904
 
271
905
  For a mode declared with `preset: :sensor`:
@@ -281,7 +915,10 @@ end
281
915
  - **sensor**: `observe` runs and its result goes into a
282
916
  `sensor.standard_flags` notification; returns the observation. An
283
917
  exception in `observe` is reported and swallowed, since sensor mode must
284
- not change behaviour.
918
+ not change behaviour. For a probe whose errors are expected, pass
919
+ `report: false` (`StandardFlags.sensor(:strict_gates, for: run, report:
920
+ false)`): the error is still swallowed and its class still rides on the
921
+ notification (and the Logger line), but nothing is reported.
285
922
  - **on**: `observe` runs, the notification fires, then `enforce` receives the
286
923
  observation; returns `enforce`'s result. Exceptions propagate.
287
924
 
@@ -410,10 +1047,13 @@ end
410
1047
  | Task | What it does |
411
1048
  |------|--------------|
412
1049
  | `bin/rails flags:list` | Every flag with its value, reason, deciding env var and remove_by (`permanent` for permanent flags). |
413
- | `bin/rails flags:stale` | Flags past `remove_by`, with the `final:` value to keep. Permanent flags never appear. |
1050
+ | `bin/rails flags:stale` | Flags and modes past `remove_by`, with the `final:` value to keep. Permanent ones never appear. With runtime rules on, also stale rules and memberships due for purge ([Stale rules](#stale-rules)). |
1051
+ | `bin/rails flags:show KEY=` | One flag's declaration, value here, ENV pin and stored rule; `KEY=cohort:<key>` for a cohort. |
1052
+ | `bin/rails flags:set` / `ramp` / `start` / `pause` / `stop` / `members:add` / `members:remove` / `purge` | Break-glass changes through the audited operations ([Rake tasks for break-glass changes](#rake-tasks-for-break-glass-changes)). |
1053
+ | `bin/rails flags:restore AT=` | Rules and memberships as they were at `AT`, from the audit log; a dry run unless `APPLY=1` ([Restore](#restore)). |
414
1054
  | `bin/rails flags:refs` | Scans `config.refs_paths` (default `app lib config`) for `on?(:k`, `off?(:k`, `mode(:k`, `variant(:k`, `evaluate(:k`, `requires_flag :k` and string keys. Exits non-zero for undeclared or tombstoned keys; warns for declared flags nothing reads. Run it in CI. |
415
- | `bin/rails standard_flags:manifest` | Writes `config/flags.manifest.json`: keys, wire names, kinds, values, audiences and defaults (and `permanent` on entries of kind `flag`), deterministically. Commit it. |
416
- | `bin/rails standard_flags:typescript` | Writes a `.d.ts` with a `Features` interface per audience (`WebFeatures`, `MobileFeatures`, …) keyed by wire name. |
1055
+ | `bin/rails standard_flags:manifest` | Writes `config/flags.manifest.json`: keys, wire names, kinds, values, audiences and defaults (and `permanent` on entries of kind `flag` and `mode`), deterministically. Commit it. |
1056
+ | `bin/rails standard_flags:typescript` | Writes a `.d.ts` with a `Features` interface per audience (`WebFeatures`, `MobileFeatures`, …) keyed by wire name, `FlagKey` and `FlagValues` (every key and its stored values), and the shapes of the MCP tools' results that the [admin page](#admin-page) uses. |
417
1057
 
418
1058
  ## Observability
419
1059
 
@@ -426,6 +1066,16 @@ end
426
1066
  | `pin_rejected.standard_flags` | An ENV pin that didn't parse. |
427
1067
  | `forbidden.standard_flags` | A `forbidden_in` flag pinned on where it's forbidden. |
428
1068
  | `legacy_env.standard_flags` | A legacy env name in use. |
1069
+ | `runtime_refresh.standard_flags` | Runtime rules reloaded (revision, rule count). |
1070
+ | `runtime_stale.standard_flags` | A runtime refresh failed; the last good rules (or code defaults) keep serving. |
1071
+ | `rule_invalid.standard_flags` | A stored rule holds something its flag can't serve. |
1072
+ | `targeting_key_missing.standard_flags` | A rule needs a unit key the context doesn't have. |
1073
+ | `change.standard_flags` | An operation's change committed (event, key or cohort, actor label, revision, store revision). The full events are `standard_flags.flag.*` and `standard_flags.cohort.*` ([Audit](#audit)). |
1074
+ | `standard_flags.members.revealed` | An operator revealed members' unit keys (actor, reason, target, counts). |
1075
+ | `standard_flags.flag.probed` | An operator evaluated a flag for one unit key (actor, reason, flag, unit, counts). |
1076
+ | `purge.standard_flags` | Memberships purged (counts). |
1077
+ | `evaluation_tracking_failed.standard_flags` | Writing `last_evaluated_at` failed; it is retried. |
1078
+ | `report_registry_full.standard_flags` | The once-per-process report registry reached its cap (1,000 entries); new warnings are no longer reported in this process. |
429
1079
 
430
1080
  Built-in subscribers: **Logger** (always), **Metrics** (`Sentry::Metrics`
431
1081
  counters when sentry-ruby is loaded) and **Sentry** (handled warnings for
@@ -434,9 +1084,33 @@ already go to `Rails.error`; enable it only when `Rails.error` isn't wired to
434
1084
  your error tracker. Add your own with
435
1085
  `config.add_notifier(->(name, payload) { ... })`.
436
1086
 
1087
+ Errors the gem reports (rejected and forbidden pins, unknown flags,
1088
+ evaluation errors, invalid runtime rules, runtime store failures) go through
1089
+ `Rails.error.report` as handled warnings. Set
1090
+ `config.error_reporter = ->(error, context) { ... }` to send them somewhere
1091
+ else instead; if it raises, the report falls back to `Rails.error`.
1092
+
437
1093
  ## Health check and diagnostics
438
1094
 
439
- With [standard_health](https://github.com/rarebit-one/standard_health):
1095
+ With [standard_health](https://github.com/rarebit-one/standard_health) 0.9 or
1096
+ later, the gem contributes its check through standard_health's load hook, so
1097
+ an app that calls `register_default_checks` gets it as `:standard_flags`
1098
+ (non-critical) with nothing else to write. Opt out or override it by name:
1099
+
1100
+ ```ruby
1101
+ StandardHealth.configure do |c|
1102
+ c.register_default_checks standard_flags: { critical: true } # or false to skip it
1103
+ end
1104
+ ```
1105
+
1106
+ It also contributes env vars to the env audit: the `STANDARD_FLAGS_<KEY>` pin
1107
+ and legacy `env:` names of every `forbidden_in:` flag, as `forbidden` in
1108
+ those environments whenever they pin the flag on. Other pins are optional,
1109
+ which the env spec has no level for, so they aren't declared. The app's own
1110
+ `env_spec` entry for a name wins.
1111
+
1112
+ On older standard_health, or without `register_default_checks`, register it
1113
+ yourself:
440
1114
 
441
1115
  ```ruby
442
1116
  StandardHealth.configure do |c|
@@ -444,9 +1118,14 @@ StandardHealth.configure do |c|
444
1118
  end
445
1119
  ```
446
1120
 
447
- The check fails when a `forbidden_in` flag is pinned on, and warns on
448
- unparseable pins, legacy names in use, flags past `remove_by`, and
449
- `STANDARD_FLAGS_*` variables that match no flag. standard_health has no
1121
+ The check fails when a `forbidden_in` flag is pinned on, or when runtime
1122
+ rules are on and their tables are missing. It warns on unparseable pins,
1123
+ legacy names in use, flags past `remove_by`, `STANDARD_FLAGS_*` variables that
1124
+ match no flag, a runtime store that can't be reached (flags keep serving
1125
+ through a database blip, so this isn't a failure), a stale runtime snapshot,
1126
+ prepared statements being off (see [Privacy](#privacy)), a missing
1127
+ `standard_flags_state` row, and runtime rules for
1128
+ undeclared or tombstoned keys. standard_health has no
450
1129
  warning status, so warnings ride on the row (`warnings:`) and the check stays
451
1130
  `:ok`; pass `warn_as: :fail` to let them degrade the tier. It is non-critical
452
1131
  by default. There is no dependency on standard_health unless you reference
@@ -455,8 +1134,97 @@ the check.
455
1134
  `StandardFlags::Diagnostics.report` returns the same picture as a hash for a
456
1135
  diagnostics page: each flag's value, reason, deciding variable and whether
457
1136
  it is permanent, plus
458
- forbidden, rejected, legacy and unknown pins and stale flags. It contains
459
- variable names only, never raw environment values.
1137
+ forbidden, rejected, legacy and unknown pins and stale flags. With runtime
1138
+ rules on it adds each flag's `rule_status` and a `runtime:` section (store,
1139
+ readiness, any unreachable error class, store warnings, revision, snapshot
1140
+ age, staleness and each rule's status), and
1141
+ `flags:list` gains a `rule` column and a header line with the revision and
1142
+ age. It contains variable names only, never raw environment values.
1143
+
1144
+ ## OpenFeature
1145
+
1146
+ Apps that read flags through the
1147
+ [openfeature-sdk](https://github.com/open-feature/ruby-sdk) gem can put the
1148
+ registry behind it. The SDK is optional: standard_flags doesn't depend on it,
1149
+ and nothing loads the provider until you require it.
1150
+
1151
+ ```ruby
1152
+ # Gemfile
1153
+ gem "openfeature-sdk"
1154
+
1155
+ # config/initializers/open_feature.rb
1156
+ require "standard_flags/open_feature"
1157
+
1158
+ OpenFeature::SDK.configure do |config|
1159
+ config.set_provider(StandardFlags::OpenFeature::Provider.new)
1160
+ end
1161
+
1162
+ client = OpenFeature::SDK.build_client
1163
+ client.fetch_boolean_value(flag_key: "new_checkout", default_value: false,
1164
+ evaluation_context: OpenFeature::SDK::EvaluationContext.new(targeting_key: account.id.to_s))
1165
+ ```
1166
+
1167
+ Requiring `standard_flags/open_feature` without the SDK raises a `LoadError`
1168
+ that says to add it. Each fetch walks the same chain as
1169
+ `StandardFlags.evaluate`, so test overrides, guards, pins and runtime rules
1170
+ all apply.
1171
+
1172
+ | Kind | Fetch | Value |
1173
+ |---|---|---|
1174
+ | `flag`, `kill_switch`, `compat` | `fetch_boolean_value` | `true` / `false` (variant `"on"` / `"off"`) |
1175
+ | `mode` | `fetch_string_value` | the value's name, e.g. `"sensor"` |
1176
+ | `experiment` | `fetch_string_value` | the variant |
1177
+
1178
+ - **Mismatches.** Any other pairing, and every number, integer, float or
1179
+ object fetch, returns your default with `TYPE_MISMATCH`, reported once.
1180
+ - **Unknown keys** return your default with `FLAG_NOT_FOUND`, even when
1181
+ `config.strict` is on. The provider never raises.
1182
+ - **Reasons and error codes** map one to one. `ENV_PIN` and `KILL_SWITCH`
1183
+ pass through as custom reasons, which OpenFeature allows.
1184
+ - **`flag_metadata`** carries `kind`, plus `rule_id` and `source_env_var`
1185
+ when they are set.
1186
+ - **Errors serve your default.** The SDK client replaces the value with
1187
+ the caller's default whenever there is an error code. So through OpenFeature,
1188
+ a flag's `fail:` value (a kill switch failing open, say), the
1189
+ fallthrough served with `TARGETING_KEY_MISSING`, and the decision made when
1190
+ the membership lookup fails (core still decides by segment, percentage or
1191
+ fallthrough but marks it `ERROR`/`GENERAL`) never reach the caller. Pass
1192
+ the default you want on failure.
1193
+ - **Lifecycle.** `metadata.name` is `"standard_flags"`. There is no `init`,
1194
+ so the provider is ready as soon as it is set, and it emits no events;
1195
+ `shutdown` does nothing.
1196
+
1197
+ The evaluation context becomes a `StandardFlags::Context`:
1198
+
1199
+ - `targeting_key` is the key of the flag's declared unit.
1200
+ - A field named after a unit (`organization`, say) sets that unit's key. For
1201
+ a flag on that unit, it wins over `targeting_key`.
1202
+ - `platform`, `appVersion` (or `app_version`) and `build` become the client,
1203
+ for client conditions.
1204
+ - `env` is ignored unless you construct the provider with
1205
+ `Provider.new(allow_env_override: true)`. Then it picks the environment for
1206
+ per-environment defaults. It never relaxes a `forbidden_in:` guard, which
1207
+ also checks the process's own environment. It is off by default because
1208
+ `env` is a common attribute name in merged global, transaction and client
1209
+ contexts.
1210
+
1211
+ Other fields are ignored. The flag's own unit key (its unit's field, else
1212
+ `targeting_key`) must be a String, Symbol or Integer; anything else (a Hash,
1213
+ say) returns your default with `INVALID_CONTEXT`. Other units' fields that
1214
+ aren't scalars are dropped, so structured attributes in a merged context
1215
+ don't break flags that don't use them.
1216
+
1217
+ **Keys are used as given.** A unit's `from:` and `key:` turn records into
1218
+ keys, and OpenFeature callers already pass keys, so the provider applies
1219
+ neither. Pass the key exactly as runtime rules store it: `record.id.to_s` by
1220
+ default, or whatever your `key:` lambda returns (the normalised phone number,
1221
+ not the raw one).
1222
+
1223
+ **The segment resolver gets keys too.** `config.segment_resolver` receives
1224
+ the same keys-only context, so a resolver written for records
1225
+ (`context.account.plan`) would raise, and every segmented rule would serve
1226
+ your default with `GENERAL`. Write it to accept a key string as well as a
1227
+ record; see the example under [Runtime rules](#runtime-rules).
460
1228
 
461
1229
  ## Testing
462
1230
 
@@ -476,10 +1244,40 @@ it "shows the new checkout", flags: { new_checkout: true } do
476
1244
  end
477
1245
  ```
478
1246
 
479
- Overrides are the first evaluation layer, so they beat guards, ENV pins and
480
- defaults without touching `ENV`. Unknown keys, wrong kinds and undeclared
1247
+ Runtime rules, held in an in-memory store for the example (no database,
1248
+ whatever the app's runtime configuration):
1249
+
1250
+ ```ruby
1251
+ with_rule(:new_checkout, percentage: 5_000) # running, 50%
1252
+ with_rule(:new_checkout, status: :stopped, stop: true)
1253
+ with_rule(:strict_gates, fallthrough: :sensor, platforms: %w[ios], versions: { ios: ">= 2.0" })
1254
+ with_rule(:home_hero, variants: { "control" => 5_000, "savings" => 5_000 })
1255
+ with_members(:new_checkout, account, value: false) # a deny; records or keys
1256
+ with_cohort(:staff, unit: :account, members: [ alice, bob ])
1257
+ with_rule(:new_checkout, cohorts: { staff: true })
1258
+ ```
1259
+
1260
+ Salts and hash versions default to the flag's `bucketing:`, else the key and
1261
+ version 2. Values are checked against the declaration.
1262
+
1263
+ Overrides are the first evaluation layer, so they beat guards, ENV pins,
1264
+ runtime rules and defaults without touching `ENV`. Unknown keys, wrong kinds and undeclared
481
1265
  values raise; unknown keys raise on read too (strict mode); everything resets
482
- after each example.
1266
+ around each example.
1267
+
1268
+ Every helper works in the example, in a `before` hook, or in an `around`
1269
+ hook that wraps `example.run`:
1270
+
1271
+ ```ruby
1272
+ around { |example| with_flag(:new_checkout, true) { example.run } }
1273
+ ```
1274
+
1275
+ The reset runs in a config-level `around` hook, outside every group-level
1276
+ one. Overrides set before an example starts (in `before(:context)`, at load
1277
+ time, or in a `config.around` registered before `require
1278
+ "standard_flags/rspec"`) would be discarded, so the example fails with an
1279
+ error that says so. `flags:` metadata is applied in `before`, so it wins
1280
+ over an `around` override of the same key.
483
1281
 
484
1282
  ### Testing a guard
485
1283
 
@@ -514,12 +1312,15 @@ context in, the expected value, variant, reason, error code and deciding
514
1312
  variable out. `bucket_vectors.json` pins test vectors for every bucketing
515
1313
  version. The Ruby suite runs every case. Evaluators in other languages (a
516
1314
  Kotlin or TypeScript client, say) run the same files, so they cannot drift
517
- from the server on what a flag evaluates to.
1315
+ from the server on what a flag evaluates to. `runtime/*.json` adds runtime
1316
+ rules: each case's rule, cohorts and memberships plus a context (unit keys,
1317
+ client, segments) in; value, variant, reason, error code and `rule_id` out,
1318
+ including the v1 and v2 bucket boundaries.
518
1319
 
519
1320
  ## Bucketing
520
1321
 
521
1322
  `StandardFlags::Bucket` holds the bucketing contract for percentage rollouts
522
- and experiments. It is not used by evaluation yet.
1323
+ and variant splits in runtime rules.
523
1324
 
524
1325
  ```ruby
525
1326
  StandardFlags::Bucket.v1(salt, unit_key) # SHA-256("salt:unit_key")[0, 15] hex % 10_000
@@ -531,13 +1332,16 @@ StandardFlags::Bucket.sql_v2(column: "devices.id") # the Postgres twin; bind
531
1332
  Buckets are basis points (0–9,999). A nil or blank unit key returns nil (the
532
1333
  caller maps it to `TARGETING_KEY_MISSING`), never a random bucket. These
533
1334
  functions are permanent: a new algorithm gets a new version and existing
534
- flags keep theirs.
1335
+ flags keep theirs. The Postgres CI job checks `sql_v2` against `v2` for
1336
+ every vector.
535
1337
 
536
1338
  ## Roadmap
537
1339
 
538
1340
  Phase 2 adds runtime rules stored in the database (changes without a
539
1341
  redeploy, allow and deny lists, cohorts, sticky percentage rollouts with
540
- per-flag salts), audited write operations and an admin generator. Phase 3
1342
+ per-flag salts), audited write operations and an admin generator. The read
1343
+ path, the operations, the rake tasks, the MCP tools, the admin generator
1344
+ and `flags:restore` are done; an OpenFeature provider comes next. Phase 3
541
1345
  adds client delivery: an OpenFeature remote-evaluation (OFREP) endpoint,
542
1346
  client version targeting, a minimum-version endpoint and the manifest
543
1347
  contract checked in client CI. Phase 4 adds experiment exposure tracking and