quonfig 1.7.2 → 1.9.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 07d679520810cf5814af80cd173f859976ce05ccd24f2c03bcbd417b57565a17
4
- data.tar.gz: aebf8fecb3821bd58cfa1465028ddefadf977e1c4c30d11f18e486ef2c290e67
3
+ metadata.gz: 06b78bb9ba3c5950d54b844388ca57e91c23c7bf4cb595c82c57738e807a1716
4
+ data.tar.gz: be216cc0d6ea8cee975bc799b94ac2f5a97829dae7fcb4056fded44835deb918
5
5
  SHA512:
6
- metadata.gz: 8823f04fc9b80149680bb384355309f2df1cca790932ede846c56f2a116f0aa9ae88858f956b43c11360aa546e979777652541e027a1865246335564c2d33b1a
7
- data.tar.gz: 1f930fffeba37875820d6871d1b9ec83981579856d12e79a5c812919a1a41f9d262618450e986d138bd1bdd84d69eb9fd4a240bd678cecdfe3bf464c8cd25aa3
6
+ metadata.gz: 3abbf9a8a7afe7883670d60869289fab0e1263d56a309713c89dc3d187fe9e8460905ae6d89f98bf3c1bfc17c45d81238abdc3cb693bf892aace508fff06ea59
7
+ data.tar.gz: fe1b42b9a3b97d41eabad20fd06610d3a7b237226e32b7af76463f98d5ee7425c0efe6958babbe4d9d0ccaf633d5d8b7c0d587a3245f2a9517534133b4691021
data/CHANGELOG.md CHANGED
@@ -1,5 +1,46 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.9.0 - 2026-10-20
4
+
5
+ - **UPGRADE: SSE reports `connected` at the first frame, not at the 200 response (qfg-goi1.10.9).** A stream connection now counts as connected, for `connection_state`, the reconnect backoff and the fallback poller, only after it delivers its first valid frame: a config envelope or a keepalive. Before, it counted as soon as the 200 response headers arrived.
6
+ - Against Quonfig's servers the headers and the first frame arrive together, so you should see no difference.
7
+ - `connection_state` now reports `:disconnected` (then `:falling_back`) when the stream ends before any frame, where it used to keep reporting `:connected` on stale config; a keepalive now counts as a live stream, so a quiet workspace no longer starts fallback polling while its stream is healthy.
8
+ - A connection that closes before any frame is now a failed attempt. The reconnect delay grows, the client reports disconnected, and the fallback poller takes over after its usual threshold.
9
+
10
+ Before this change, a server that answered 200 and closed at once left the SDK on stale config indefinitely while `connection_state` reported `:connected`.
11
+ - **UPGRADE: may change returned values. Minor: one config that fails to load no longer raises out of every read of its key (qfg-krjt).** A config whose rule, criterion or default has the wrong shape (for example `rules: ["oops"]`, `criteria: "oops"` or `default: "oops"`), or whose weighted value has a `weight` that is not an integer (a string, float or null), used to install and then raise `NoMethodError` or `TypeError` out of `get`, `enabled?` and the typed getters on every read of that key. That entry is now skipped when the payload is decoded (HTTP, SSE or a datadir file) with a WARN naming its key, the rest installs, and the skipped key reads as not found (your default, `false` from `enabled?`, or `FLAG_NOT_FOUND` in the `*_details` getters). A payload whose every entry fails is still rejected (a failed fetch leg on HTTP, a dropped event on SSE, a load error in datadir mode), so it cannot install as an empty workspace. A weighted value with no `weight` now counts as 0 instead of raising. Matches sdk-go, sdk-node and sdk-python. Test: `test/test_malformed_config_skip.rb`.
12
+ - **Changed (minor): the first-frame rule in the SSE worker (qfg-goi1.10.43).** A keepalive (a comment-only block such as `: keepalive`) now resets the reconnect backoff to its initial delay and cancels the fallback poller's engage timer (or stops an engaged poller), like an envelope; it does not advance `last_successful_refresh`. A 200 stream that ends before its first frame now calls the internal `on_error` path (logged at WARN), so the poller engages at once if SSE never connected, or after 2x the poll interval following a mid-life drop. `connection_state` still stays `:connected` across a clean reconnect after a session that delivered a frame, but only until that next connection either delivers its own first frame or ends without one. Contract: integration-test-data `v2026.10.16.4`, supervisor contract Test 9 (a)-(d) and the Test 2 reset amendment, in `test/test_sse_first_frame.rb`.
13
+ - **Tests: unit and release tests now run integration-test-data `v2026.10.16.4`.** It also moves the two `get_or_raise` init-timeout cases to `http://192.0.2.1:1` (qfg-goi1.6). The chaos workflows stay on `v2026.10.16.2`.
14
+ - **Fix (patch): `Client#stop` no longer leaks the SSE worker thread or waits 2 seconds (qfg-yrly).** Stopping a client with a live stream left the SSE worker blocked forever: the worker left the stream with a `break` inside `read_body`, and Net::HTTP then read the rest of the endless stream to finish the response. `stop` waited 2s for the worker and then returned with the thread still running, and the thread kept the old client alive in memory. The SDK also closes the stream when it enters auth-failed, so each auth-failed entry leaked one thread too. The worker now leaves the stream without that read, so `stop` returns promptly and the thread exits. Tests: `test/test_sse_close_during_stream.rb` (close during a live stream and during a blocked read), and the close assertion in `test/test_sse_config_client.rb` now checks the real worker thread.
15
+ - **Fix (patch): a config update is now applied to the store all at once (qfg-i86q).** The SDK wrote each config of a new envelope into the live store one key at a time, so a request evaluating during that write could see a flag from the new envelope with a segment from the old one, or a key that was briefly missing, and get the wrong value with no error or log. Each install (SSE, polling, the initial fetch and a datadir reload) now builds the new set of configs first and swaps it in with one write, like sdk-go, and each lookup reads one snapshot from start to finish (the flag, its segments and any `decryptWith` key). `ConfigStore` gains `replace_all`; `get`, `set`, `delete`, `keys` and `all_configs` behave as before. Test: `test/test_config_loader_atomic_install.rb` (a reader during 198 installs; before this fix about 40% of its reads were wrong).
16
+
17
+ ## 1.8.0 - 2026-10-16
18
+
19
+ - **UPGRADE: retry cadence and log levels change after a rejected 401/403/404/410 fetch cycle; a revoked key logs one config ERROR. `terminal_failure?` changes meaning. Minor (1.8.0): one auth-failure rule across the SDKs (qfg-goi1.10.26). This reverses the qfg-i5xv latch.**
20
+ - **No latch.** Before, the first SSE 401, 403 or 404 stopped the stream for the life of the client and kept the fallback poller off, so a key that was rejected once (or a transient primary 401) left the client on stale config until it was rebuilt. Now an auth-class stream response (401, 403, 404, and now 410) keeps the normal reconnect ladder, and the fallback poller engages on its usual schedule (at once if SSE never connected, 2x the poll interval after a mid-life drop).
21
+ - **Auth-failed.** A poll cycle (the fallback poller's, or each poll with `enable_sse: false`) that gets no 200 or 304 on any leg and a 401/403/404/410 on the primary leg puts the client in auth-failed. Primary rejected + secondary 503 or timeout enters; primary 503 + secondary rejected does not. While auth-failed: no stream, no polling, one fetch probe across every leg every 150-300s (with `enable_sse: false`, the larger of that and the poll interval), with no doubling and no give-up. The first probe that gets a valid 200 or a 304 on any leg installs it, logs one INFO and resumes streaming (from its base backoff) and polling. `connection_state` is `:disconnected` while auth-failed, never `:falling_back`.
22
+ - **Logging.** On entry: one ERROR, `config fetch rejected (HTTP <status> from <host:port>) ...`, naming the status and host, never the key, in place of that cycle's per-leg lines. Probes log at DEBUG. Before entry, an SSE 401/403/404/410 logs one WARN per status (re-armed by a 200) and DEBUG after that; before, a 401/403/404 logged one ERROR and a 410 logged two ERRORs per attempt. Other SSE errors (5xx) log as before.
23
+ - **`terminal_failure?` now means "auth-failed right now".** It turns true when a poll cycle is rejected as above (about 120s after a mid-life stream drop, at once if SSE never connected), not on the first SSE 401, and it goes back to false when a probe is accepted. Code that rebuilt the client when it saw `true` can stop doing so; the client recovers by itself. Name, signature and return type are unchanged.
24
+ - `SSEConfigClient::SSEHTTPTerminalError` and `TERMINAL_HTTP_CODES` are deprecated aliases of the new `SSEHTTPAuthError` and `AUTH_HTTP_CODES` (`[401, 403, 404, 410]`).
25
+ - Tests: supervisor contract Test 8 (a)-(g) (integration-test-data `v2026.10.16`, already contained in the pinned `v2026.10.16.1`) in `test/test_supervisor_auth_failure.rb`, plus the repro8 regression (a revoked key on every leg: one poll cycle, then probes, then recovery).
26
+ - **UPGRADE: may change who matches a rule. Minor: one set of rule-operator semantics across the SDKs (qfg-goi1.5.7).** Pass dates to `PROP_BEFORE` / `PROP_AFTER` rules as epoch milliseconds (an Integer, a Float, or an all-digit string) or as an ISO 8601 / RFC3339 timestamp with `Z` or a numeric offset, such as `2025-01-01T00:00:00Z` or `2025-01-01T09:00:00+09:00`. Three changes:
27
+ - **Dates are strict on both sides.** The context value and the rule's date are now read with one grammar: epoch ms, or RFC3339 with an uppercase `T` and a `Z` or `+hh:mm` / `-hh:mm` offset (fractional seconds allowed, truncated to ms). `DateTime.parse` is gone, so a date-only string (`"2020-01-01"`), an offset-less one (`"2020-01-01T00:00:00"`, which was read as UTC) and free-form text (`"Jan 1 2020"`) are not dates any more, and a rule comparing them does not match. Digit strings no longer accept `Integer()` extras such as `"0x10"` or `"1_000"`. A `Float::NAN` or `Float::INFINITY` context date no longer raises `FloatDomainError`; it does not match.
28
+ - **Whole-number floats compare as plain digits.** In `PROP_IS_ONE_OF` / `PROP_IS_NOT_ONE_OF`, the starts-with / ends-with / contains operators and `HIERARCHICAL_MATCH`, a context value of `1.0`, `1234567.0` or `5e9` now reads as `"1"`, `"1234567"`, `"5000000000"` (it was `"1.0"`, `"1234567.0"`, `"5.0e9"`), so `is one of ["1234567"]` matches it and a list holding `"1.0"` no longer does. Non-integral floats (`1.5`) and Integers are unchanged; booleans still read `"true"` / `"false"`.
29
+ - **Abbreviated versions.** `PROP_SEMVER_*` reads `"2"` as `2.0.0` and `"2.0"` / `"4.1"` as `2.0.0` / `4.1.0`, on the context and the rule side, so an app reporting `"4.1"` now matches a `4.1.0` rule. A prerelease or build suffix still needs the full `x.y.z`, and a `v` prefix is still not a version. `SemanticVersion.parse` itself stays strict.
30
+ Matches integration-test-data `v2026.10.16.1` and the other SDKs.
31
+ Approved as minors under Decision 1 (qfg-goi1.5, 2026-10-09).
32
+ - **UPGRADE: may change returned values. Minor: JSON values are returned as a fresh copy on every call (qfg-goi1.10.3).** `get`, `get_json` and `get_json_details` (also on `BoundClient`) used to return the SDK's own Hash or Array for a JSON config. If your code changed the result (for example added a key or appended to a list), every later read in the process saw the change. Each call now returns its own copy of the Hashes and Arrays, so changes stay local. What changes for you: two calls no longer return the same object (`equal?` is false; `==` is still true), and code that relied on mutating the result to change config no longer does. Values are not frozen, so code that mutates its own copy keeps working. Strings are not copied: `get_string` and the strings inside a JSON value are the same objects as before. Matches sdk-go, sdk-net and sdk-java.
33
+ - **CI: unit and release tests now run integration-test-data `v2026.10.16.1` (qfg-goi1.5.7).** It adds the OPERATOR EDGES cases (bool and digit-string one-of, int ranges, prerelease and abbreviated semver, strict dates). The chaos workflows stay on `v2026.10.03`.
34
+ - **Fix (patch): `EnvVarParseError` messages now use the cross-SDK wording (qfg-goi1.10.21).** An ENV_VAR value that cannot be converted to the config's type now raises with `environment variable "<NAME>" cannot be converted to <type> for config "<key>"` (for example `... cannot be converted to int for config "my.key"`), the template pinned by integration-test-data `v2026.10.12`. It was `Evaluating <key> couldn't coerce <NAME> to <type>`. A malformed stored duration reads `stored value cannot be converted to duration for config "<key>"`. The value is still never in the message. Only the message text changes; the exception class and when it is raised are unchanged.
35
+ - **CI: unit, contract and release tests now run integration-test-data `v2026.10.12` (qfg-goi1.10.21).** It adds the coercion-message cases above, confidential weighted-variant and ENV_VAR telemetry redaction cases, and an env-scoped decryption key case. The chaos workflows stay on `v2026.10.03`.
36
+ - **Docs: the README now says that the SDK adds the `qfg login` email to every evaluation as `quonfig-user.email` by default, and how to turn it off (`enable_quonfig_user_context: false` or `QUONFIG_DEV_CONTEXT=false`) (qfg-goi1.2.40).** No code change.
37
+ - **Fix (security, patch): a `confidential` or `decryptWith` variant inside a weighted rollout is now redacted in telemetry (qfg-goi1.2.39).** The evaluation-summary redaction looked only at the outer `weighted_values` wrapper, which is never flagged, so the selected variant went out as `selectedValue` in plaintext (for `decryptWith`, the decrypted secret). The selected variant is now sent as `*****<md5[0,5]>` over its stored value (the ciphertext for `decryptWith`), the same as a non-rollout secret and the same as sdk-go, sdk-node and sdk-java.
38
+ - **Fix (patch): `Client#stdlib_formatter` no longer raises out of the host app's `::Logger` calls (qfg-goi1.2.28).** `Client#get` raises on a resolution error (for example `MissingEnvVarError` when the log level is provided by an env var that is unset on this host, or `DecryptionError`) even when a default is passed, and the formatter let that escape, so every `logger.info` raised. The formatter now emits the line in that case, the same as `SemanticLoggerFilter` since 1.7.2. `Client#should_log?` itself is unchanged.
39
+ - **Fix (patch): example-context telemetry now copies the context when it is recorded (qfg-goi1.2.35).** The SDK kept the caller's nested Hashes and Arrays by reference and serialized them later on the telemetry thread, so changing them after `get` changed what was sent. A `Float::NAN` or `Float::INFINITY`, or a Hash or Array that contains itself, made the whole telemetry window fail to serialize, so that window's evaluation summaries, context shapes and example contexts were all lost. Now, at record time: nested Hashes and Arrays are copied (keys as strings, up to 32 levels deep), strings are copied, symbols become strings, NaN and Infinity become `null`, the edge that closes a cycle is left out, and any other object is sent as its `to_s`, as before (so a UUID-like key object still makes the example reportable). Only a value whose `to_s` raises is left out. Context shapes are unchanged. Evaluation is unchanged.
40
+ - **Tests: the datadir auto-reload burst test no longer sleeps between writes (qfg-goi1.2.29).** A 10ms sleep between five rewrites could outlast the 150ms debounce on a starved CI runner, so the test saw more than one reload (it failed once on Ruby 3.2 CI). The writes are now back to back, and a new filesystem-free test drives `DatadirWatcher` directly: events in one window fire once, a later event fires again, and `stop` cancels a pending fire. No library change.
41
+ - **Fix (patch): an install interrupted part-way through the store write is now repaired by the next delivery of the same envelope (qfg-goi1.10.2).** The SDK recorded the new config generation before it wrote the configs into the store, so an interrupt during the write (for example `Thread#raise` or `Timeout`) left a partly updated store marked as fully installed, and the same-generation redelivery that follows (SSE re-sends the current envelope on every connect) was ignored as a duplicate. The generation now advances only after the store write.
42
+ - **Fix (patch): the SSE line reader no longer rescans its whole buffer on every chunk (qfg-goi1.10.2).** A long SSE line (a large config envelope) delivered in small chunks cost O(n^2) time: 100,000 one-byte chunks took about 9 seconds. Scanning now resumes where the previous chunk stopped, and the consumed bytes are dropped once per chunk instead of once per line. Parsing results are unchanged; there is still no size cap.
43
+
3
44
  ## 1.7.2 - 2026-10-09
4
45
 
5
46
  - **Fix (security): `TypeMismatchError` and `EnvVarParseError` messages no longer include the value (qfg-goi1.2.11).** Reading a `confidential` or `decryptWith` config through the wrong typed getter (for example `get_int` on a secret) put the decrypted plaintext into the exception message and into `*_details.error_message`, which end up in logs and error trackers. An unparseable ENV_VAR or a malformed stored duration put the raw value into `EnvVarParseError`. The messages now name the key, the expected type and the actual class (`TypeMismatchError`), or the key, the env var name (or `stored value`) and the target type (`EnvVarParseError`). The doubled word in `expected expected Integer` is fixed. Only the message text changes; the exception classes and when they are raised are unchanged.
data/README.md CHANGED
@@ -82,6 +82,16 @@ bound.get_int('rate-limit')
82
82
  > `in_context` is a deprecated alias of `with_context` kept for backward
83
83
  > compatibility through 1.0.0. New code should use `with_context`.
84
84
 
85
+ ### Developer context (on by default)
86
+
87
+ On a machine where someone ran `qfg login`, the SDK reads the signed-in email
88
+ from `~/.quonfig/tokens.json` and adds it to every evaluation as
89
+ `quonfig-user.email`, so rules can target it and it reaches telemetry example
90
+ contexts; pass `enable_quonfig_user_context: false` or set
91
+ `QUONFIG_DEV_CONTEXT=false` to turn it off. Servers without that file are
92
+ unaffected, and a `quonfig-user` context you pass in `global_context:`
93
+ replaces it.
94
+
85
95
  ## Datadir / offline mode
86
96
 
87
97
  For tests, CI, or air-gapped environments, point the client at a local workspace
@@ -246,6 +256,7 @@ for the cross-SDK story (sdk-node, sdk-go, sdk-ruby, sdk-python, sdk-java).
246
256
  | `QUONFIG_BACKEND_SDK_KEY` | SDK key used to authenticate against the Quonfig API. Used when `sdk_key:` is omitted. |
247
257
  | `QUONFIG_DIR` | Path to a workspace directory. When set, the SDK runs in datadir/offline mode. |
248
258
  | `QUONFIG_ENVIRONMENT` | Environment name (`production`, `staging`, `development`) evaluated in datadir mode. |
259
+ | `QUONFIG_DEV_CONTEXT` | `false` turns off the developer context (`quonfig-user.email` from `qfg login`). An explicit `enable_quonfig_user_context:` wins. See [Developer context](#developer-context-on-by-default). |
249
260
  | `QUONFIG_DOMAIN` | Base domain used to derive api, sse, and telemetry URLs. Defaults to `quonfig.com`. Set to `quonfig-staging.com` to point at staging. Explicit `api_urls:` / `telemetry_url:` kwargs override this. |
250
261
 
251
262
  ## Constructor options
@@ -279,6 +290,7 @@ Quonfig::Client.new(
279
290
  | `init_timeout_ms` | `Integer` (ms) | `10_000` | Maximum time to wait for the initial config load, in milliseconds. Deprecated alias: `initialization_timeout_sec` (seconds, multiplied by 1000 internally). |
280
291
  | `on_no_default` | `Symbol` | `:raise` | Behavior when a key has no value and no default: `:raise` (raise `Quonfig::Errors::MissingDefaultError`) or `:return_nil`. |
281
292
  | `global_context` | `Hash` | `{}` | Context applied to every evaluation. |
293
+ | `enable_quonfig_user_context` | `Boolean` or `nil` | `nil` (on, unless `QUONFIG_DEV_CONTEXT=false`) | Add the `qfg login` email as `quonfig-user.email`. See [Developer context](#developer-context-on-by-default). |
282
294
  | `datadir` | `String` | `ENV['QUONFIG_DIR']` | Path to a local workspace. When set, the SDK runs offline from disk. |
283
295
  | `environment` | `String` | `ENV['QUONFIG_ENVIRONMENT']` | Environment to evaluate in datadir mode. Required when `datadir` is set. |
284
296
  | `data_dir_auto_reload` | `Boolean` | `false` | Datadir mode only. When `true`, the SDK watches the datadir and re-reads the envelope when files change. See [Datadir mode: auto-reload on file changes](#datadir-mode-auto-reload-on-file-changes). |
@@ -664,6 +676,18 @@ process.
664
676
 
665
677
  There is intentionally no `client.healthy?` primitive.
666
678
 
679
+ ### A rejected SDK key
680
+
681
+ When a whole config fetch cycle is rejected (no 200 or 304 on any leg, and a
682
+ 401, 403, 404 or 410 on the primary), the SDK key is invalid or revoked. The
683
+ SDK logs one ERROR naming the status and host, stops streaming and polling,
684
+ and retries with one fetch every 150-300 seconds for as long as the process
685
+ runs. The first accepted fetch installs the config, logs one INFO, and resumes
686
+ streaming and polling on its own; you do not need to rebuild the client. While
687
+ this lasts `client.connection_state` is `:disconnected` and
688
+ `client.terminal_failure?` is `true`. A rejection on the stream alone never
689
+ does this: the SDK keeps reconnecting and its fallback poller decides.
690
+
667
691
  ## Telemetry
668
692
 
669
693
  With an SDK key the client sends usage telemetry to `telemetry_url` so the
@@ -21,6 +21,10 @@ module Quonfig
21
21
  class Client
22
22
  LOG = Quonfig::InternalLogger.new(self)
23
23
 
24
+ # Auth-failed probe period bounds, rule R3 (qfg-goi1.10.26).
25
+ AUTH_PROBE_MIN_SECONDS = 150.0
26
+ AUTH_PROBE_MAX_SECONDS = 300.0
27
+
24
28
  # qfg-ryov: instance registry for the Process._fork hook. Every live
25
29
  # Client is tracked here so the hook can fan out after_fork_in_child
26
30
  # across all of them without the customer needing to name a specific
@@ -86,7 +90,11 @@ module Quonfig
86
90
  @sse_state = :idle
87
91
  @sse_ever_connected = false
88
92
  @fallback_engage_timer = nil
89
- @sse_terminal_failure = false
93
+ # Auth-failed regime (rule R2-R4, qfg-goi1.10.26). Set by the poller's
94
+ # fetch cycle on entry, cleared by the first accepted probe. While set:
95
+ # no SSE, no polling, one probe per [150s, 300s]. Read by
96
+ # #terminal_failure? and #connection_state.
97
+ @auth_failed = false
90
98
  # The process that owns this client's threads, sockets, and store.
91
99
  # Re-stamped when a child takes ownership in #rebuild_in_child!. A pid
92
100
  # mismatch is PROOF that we are looking at a fork(2) child, which is
@@ -493,7 +501,7 @@ module Quonfig
493
501
  # (it had connected, it had errored, ...). None of them apply here.
494
502
  @sse_state = :idle
495
503
  @sse_ever_connected = false
496
- @sse_terminal_failure = false
504
+ @auth_failed = false
497
505
  @sse_error_callback = nil
498
506
 
499
507
  # A client that never finished network init has nothing to rebuild.
@@ -581,6 +589,9 @@ module Quonfig
581
589
  # running. Saying so is the honest answer, and a diagnostic must not
582
590
  # be what triggers a blocking fetch.
583
591
  next :initializing if @fork_rebuild_pending
592
+ # Auth-failed is not a state of its own (R6): SSE and the poller are
593
+ # off, so the client is disconnected, never falling_back.
594
+ next :disconnected if @auth_failed
584
595
  next :falling_back if @poll_supervisor&.alive?
585
596
  # Liveness beats the stored flag (qfg-lv4n.1). A client whose SSE
586
597
  # session was torn down keeps a stale @sse_state; answering
@@ -1079,31 +1090,31 @@ module Quonfig
1079
1090
  @sse_error_callback ||= ->(error) { handle_sse_error(error) }
1080
1091
  end
1081
1092
 
1082
- def handle_sse_error(error)
1083
- # qfg-i5xv: classify terminal HTTP failures (401/403/404). The same SDK
1084
- # key that won't auth over SSE won't auth over HTTP polling either, so
1085
- # we must NOT engage the Layer 2 fallback — that just moves the
1086
- # auth-failure storm from one endpoint to another. Once flipped,
1087
- # @sse_terminal_failure latches: a buggy customer retry loop cannot
1088
- # un-classify the failure by driving the state machine.
1089
- @state_mutex.synchronize { @sse_terminal_failure = true } if error.is_a?(Quonfig::SSEConfigClient::SSEHTTPTerminalError)
1093
+ def sse_connected_callback
1094
+ @sse_connected_callback ||= -> { handle_sse_state_change(:connected) unless @stopped }
1095
+ end
1096
+
1097
+ # Every SSE error, auth-class included, is an ordinary drop: SSE alone
1098
+ # never enters auth-failed (rule R2, qfg-goi1.10.26; this reverses the
1099
+ # qfg-i5xv latch). The fallback poller engages on its usual schedule and
1100
+ # its fetch cycle decides.
1101
+ def handle_sse_error(_error)
1090
1102
  handle_sse_state_change(:error)
1091
1103
  end
1092
1104
 
1093
1105
  def handle_sse_state_change(new_state)
1094
1106
  state = new_state.to_sym
1095
- ever_connected, terminal = @state_mutex.synchronize do
1107
+ ever_connected, auth_failed = @state_mutex.synchronize do
1096
1108
  @sse_state = state
1097
1109
  @sse_ever_connected = true if state == :connected
1098
- [@sse_ever_connected, @sse_terminal_failure]
1110
+ [@sse_ever_connected, @auth_failed]
1099
1111
  end
1100
1112
 
1101
1113
  return unless @options.respond_to?(:fallback_poll_enabled) && @options.fallback_poll_enabled
1102
1114
  return if @stopped
1103
- # qfg-i5xv: a terminal SSE classification suppresses polling engage in
1104
- # every branch — the customer's key is bad and HTTP polling will fail
1105
- # identically. Operators surface this via #terminal_failure?.
1106
- return if terminal
1115
+ # While auth-failed SSE is stopped; a late edge from the stream being
1116
+ # torn down changes nothing (the probe loop owns the schedule).
1117
+ return if auth_failed
1107
1118
 
1108
1119
  case state
1109
1120
  when :connected
@@ -1120,15 +1131,22 @@ module Quonfig
1120
1131
 
1121
1132
  public
1122
1133
 
1123
- # qfg-i5xv: true once the SSE layer has classified an HTTP response as
1124
- # terminal (401/403/404) — bad SDK key, revoked workspace permission,
1125
- # or wrong endpoint. The classification latches: the SDK will not
1126
- # auto-recover, and a customer-supplied retry must rebuild the client.
1127
- # Surfaced for operator alerting; `connection_state` still reports
1128
- # `:disconnected` to honor the documented connection_state vocabulary
1129
- # (supervisor-test-contract.md §"connectionState()" — values fixed).
1134
+ # True while the client is auth-failed (since 1.8.0, qfg-goi1.10.26): a
1135
+ # whole config fetch cycle got no 200/304 on any leg and a 401, 403, 404
1136
+ # or 410 on the primary leg, which means the SDK key is invalid or
1137
+ # revoked. It turns true when the fallback poller's cycle (or, with
1138
+ # +enable_sse: false+, a poll) is rejected: about 120s after a mid-life
1139
+ # stream drop, at once if SSE never connected. While true, SSE and polling
1140
+ # are off and the client sends one fetch probe every 150-300s. It goes back
1141
+ # to false on the first probe that gets a valid 200 or a 304, and the
1142
+ # client resumes streaming and polling on its own; there is no need to
1143
+ # rebuild the client.
1144
+ #
1145
+ # Before 1.8.0 this latched true on the first SSE 401/403/404 for the life
1146
+ # of the client (qfg-i5xv). +connection_state+ reports +:disconnected+
1147
+ # while this is true.
1130
1148
  def terminal_failure?
1131
- @state_mutex.synchronize { @sse_terminal_failure }
1149
+ @state_mutex.synchronize { @auth_failed }
1132
1150
  end
1133
1151
 
1134
1152
  private
@@ -1179,7 +1197,7 @@ module Quonfig
1179
1197
 
1180
1198
  @fallback_engage_timer = Thread.new do
1181
1199
  Thread.current.report_on_exception = false
1182
- sleep grace_seconds
1200
+ Quonfig::Waits.sleep(:engage, grace_seconds)
1183
1201
  @state_mutex.synchronize { @fallback_engage_timer = nil }
1184
1202
  start_polling unless @stopped
1185
1203
  end
@@ -1259,10 +1277,8 @@ module Quonfig
1259
1277
  # propagates through the auto-reload path. Records a refresh timestamp.
1260
1278
  # Caller is responsible for firing on_update.
1261
1279
  def apply_datadir_envelope(envelope)
1262
- new_keys = envelope.configs.map { |cfg| cfg['key'] }.compact.to_set
1263
- old_keys = @store.keys.to_set
1264
- (old_keys - new_keys).each { |k| @store.delete(k) }
1265
- envelope.configs.each { |cfg| @store.set(cfg['key'], cfg) }
1280
+ # One atomic swap, like a network install (qfg-i86q).
1281
+ @store.replace_all(envelope.configs.to_h { |cfg| [cfg['key'], cfg] })
1266
1282
  # qfg-pinh: evaluate against the installed envelope's meta.environment,
1267
1283
  # matching sdk-go. In datadir mode the loader stamps meta.environment =
1268
1284
  # the resolved env (the `environment:` pin or QUONFIG_ENVIRONMENT), so
@@ -1480,7 +1496,12 @@ module Quonfig
1480
1496
  @config_loader,
1481
1497
  nil,
1482
1498
  nil,
1483
- on_error: sse_error_callback
1499
+ on_error: sse_error_callback,
1500
+ # First-frame rule (qfg-goi1.10.43): connected at the connection's
1501
+ # first valid frame, keepalive included, never on the 200 headers.
1502
+ # Cancels the engage timer / disengages the poller without stamping
1503
+ # last_successful_refresh (only an install or fetch does that).
1504
+ on_connected: sse_connected_callback
1484
1505
  )
1485
1506
  @sse_client.start do |envelope, _event, _source|
1486
1507
  next if @stopped
@@ -1522,30 +1543,41 @@ module Quonfig
1522
1543
  # engage() (immediate Fetch, then ticker). A sleep-first worker made the
1523
1544
  # first post-engage data arrive a full extra interval late (~180s after
1524
1545
  # SSE loss with the default 60s interval, vs ~120s in go).
1546
+ #
1547
+ # Auth-failure rule (qfg-goi1.10.26, R2-R4): a poll cycle with no 200/304
1548
+ # on any leg and an auth-class status on the primary enters auth-failed.
1549
+ # The same worker then probes once per T in [150s, 300s] (polling mode:
1550
+ # max(T, interval)) until a probe is accepted. The flag lives on the
1551
+ # client, so a supervisor restart of this worker keeps probing.
1525
1552
  worker = lambda do |notify_delivered|
1526
1553
  loop do
1527
1554
  break if stopped_ref.call
1528
1555
 
1529
- result = @config_loader.fetch!
1530
- # Liveness honesty (qfg-41nh.6): stamp freshness only when the fetch
1531
- # actually SUCCEEDED. :updated and :not_modified (a 304, or a
1532
- # guard-rejected-but-successful response) are successes — the
1533
- # channel is healthy; :failed must NOT advance
1534
- # last_successful_refresh (pre-fix every tick stamped + notified
1535
- # regardless of outcome, so ready?/freshness reported healthy over
1536
- # an empty store through a total outage). on_update fires only on a
1537
- # real install, matching sdk-go (OnConfigUpdate fires in
1538
- # installEnvelope only).
1539
- if result != :failed
1540
- sync_evaluator_env_id!
1541
- record_refresh!
1542
- notify_delivered.call
1556
+ if auth_failed?
1557
+ Quonfig::Waits.sleep(:probe, auth_probe_wait(poll_seconds))
1558
+ break if stopped_ref.call
1559
+
1560
+ case run_auth_probe(notify_delivered)
1561
+ when :rejected then next
1562
+ when :handed_to_sse then break
1563
+ end
1564
+ # Accepted in polling mode: resume at the interval, no immediate
1565
+ # fetch (the probe just fetched).
1566
+ Quonfig::Waits.sleep(:poll, poll_seconds)
1567
+ next
1568
+ end
1569
+
1570
+ cycle = @config_loader.fetch_cycle!(log_mode: :poll)
1571
+ if cycle.auth_rejected?
1572
+ enter_auth_failed!(cycle) unless stopped_ref.call
1573
+ next
1543
1574
  end
1544
- notify_on_update_callback if result == :updated
1575
+
1576
+ after_poll_result(cycle.result, notify_delivered)
1545
1577
 
1546
1578
  break if stopped_ref.call
1547
1579
 
1548
- sleep poll_seconds
1580
+ Quonfig::Waits.sleep(:poll, poll_seconds)
1549
1581
  end
1550
1582
  end
1551
1583
 
@@ -1560,6 +1592,85 @@ module Quonfig
1560
1592
  LOG.warn "[quonfig] Layer 2 fallback poller engaged (interval=#{poll_ms}ms)"
1561
1593
  end
1562
1594
 
1595
+ # Liveness honesty (qfg-41nh.6): stamp freshness only when the fetch
1596
+ # actually SUCCEEDED. :updated and :not_modified (a 304, or a
1597
+ # guard-rejected-but-successful response) are successes — the channel is
1598
+ # healthy; :failed must NOT advance last_successful_refresh (pre-fix every
1599
+ # tick stamped + notified regardless of outcome, so ready?/freshness
1600
+ # reported healthy over an empty store through a total outage). on_update
1601
+ # fires only on a real install, matching sdk-go (OnConfigUpdate fires in
1602
+ # installEnvelope only).
1603
+ def after_poll_result(result, notify_delivered)
1604
+ if result != :failed
1605
+ sync_evaluator_env_id!
1606
+ record_refresh!
1607
+ notify_delivered.call
1608
+ end
1609
+ notify_on_update_callback if result == :updated
1610
+ end
1611
+
1612
+ def auth_failed?
1613
+ @state_mutex.synchronize { @auth_failed }
1614
+ end
1615
+
1616
+ # Rule R3: T uniform in [150s, 300s], re-drawn per probe, never doubled.
1617
+ # With SSE disabled the wait is max(T, poll interval). Internal: tests
1618
+ # reach it through Quonfig::Waits, it is not a customer option.
1619
+ def auth_probe_wait(poll_seconds)
1620
+ t = AUTH_PROBE_MIN_SECONDS + (rand * (AUTH_PROBE_MAX_SECONDS - AUTH_PROBE_MIN_SECONDS))
1621
+ t = poll_seconds if !@options.enable_sse && poll_seconds > t
1622
+ t
1623
+ end
1624
+
1625
+ # Entry (R2-R5), on the poller's thread, in this order: SSE off (stream
1626
+ # closed and its worker joined, the engage timer cancelled), the flag up,
1627
+ # then one ERROR naming the status and the primary host, never the key.
1628
+ def enter_auth_failed!(cycle)
1629
+ cancel_fallback_engage_timer
1630
+ sse = @state_mutex.synchronize do
1631
+ @auth_failed = true
1632
+ @sse_state = :idle
1633
+ s = @sse_client
1634
+ @sse_client = nil
1635
+ s
1636
+ end
1637
+ begin
1638
+ sse&.close
1639
+ rescue StandardError => e
1640
+ LOG.debug "Error closing SSE client on auth-failed entry: #{e.message}"
1641
+ end
1642
+ LOG.error "[quonfig] config fetch rejected (HTTP #{cycle.primary_status} from #{cycle.primary_host}): " \
1643
+ 'the SDK key is invalid or revoked (check the SDK key); streaming and polling stopped, ' \
1644
+ 'retrying every few minutes until it is accepted'
1645
+ end
1646
+
1647
+ # One auth-failed probe: a fetch cycle across every leg (R3), logged at
1648
+ # DEBUG only. The first valid 200 or a 304 on any leg exits (R4): one
1649
+ # INFO, and SSE restarts from its base backoff (a brand-new stream
1650
+ # client), handing the update channel back from this poller. With SSE
1651
+ # disabled the poller resumes polling. Returns :rejected, :handed_to_sse
1652
+ # or :resume_polling.
1653
+ def run_auth_probe(notify_delivered)
1654
+ cycle = @config_loader.fetch_cycle!(log_mode: :probe)
1655
+ if cycle.result == :failed
1656
+ LOG.debug "[quonfig] auth-failed probe rejected (HTTP #{cycle.primary_status} from #{cycle.primary_host}); " \
1657
+ 'retrying later'
1658
+ return :rejected
1659
+ end
1660
+
1661
+ after_poll_result(cycle.result, notify_delivered)
1662
+ handing_to_sse = @options.enable_sse && !@stopped
1663
+ # Stop this poller first (from its own thread: WorkerSupervisor#stop only
1664
+ # flags it) so connection_state never reads falling_back on the way out.
1665
+ stop_fallback_poller('auth-recovered') if handing_to_sse
1666
+ @state_mutex.synchronize { @auth_failed = false }
1667
+ LOG.info '[quonfig] config fetch accepted; leaving auth-failed and resuming streaming and polling'
1668
+ return :resume_polling unless handing_to_sse
1669
+
1670
+ start_sse
1671
+ :handed_to_sse
1672
+ end
1673
+
1563
1674
  # Invoke the customer-supplied on_update callback under a rescue. A raise
1564
1675
  # here is the customer's bug, but it must NOT take down the SSE listener
1565
1676
  # or polling supervisor. Log at ERROR with a message containing
@@ -1794,7 +1905,7 @@ module Quonfig
1794
1905
  end
1795
1906
 
1796
1907
  def malformed_stored_duration_error(result)
1797
- Quonfig::Errors::EnvVarParseError.new(result.raw_value, result.config || {}, 'stored value')
1908
+ Quonfig::Errors::EnvVarParseError.new(result.raw_value, result.config || {}, nil, stored: true)
1798
1909
  end
1799
1910
 
1800
1911
  def malformed_duration(key, default, error)