quonfig 1.2.0 → 1.4.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.
@@ -21,14 +21,16 @@ module Quonfig
21
21
  LOG = Quonfig::InternalLogger.new(self)
22
22
 
23
23
  # qfg-ryov: instance registry for the Process._fork hook. Every live
24
- # Client is tracked here so the hook can fan out before_fork_in_parent /
25
- # after_fork_in_child across all of them without the customer needing to
26
- # name a specific instance. ObjectSpace::WeakMap means a Client that goes
27
- # out of scope is GC'd without leaking through this registry. Stopped
28
- # Clients stay in the registry until GC; both fork hooks early-return on
29
- # +@stopped+ so a stopped instance is effectively a no-op. (We don't use
30
- # WeakMap#delete because it was added in Ruby 3.3 and the matrix still
31
- # includes 3.2.)
24
+ # Client is tracked here so the hook can fan out after_fork_in_child
25
+ # across all of them without the customer needing to name a specific
26
+ # instance. ObjectSpace::WeakMap means a Client that goes out of scope is
27
+ # GC'd without leaking through this registry. Stopped Clients stay in the
28
+ # registry until GC; after_fork_in_child early-returns on +@stopped+ so a
29
+ # stopped instance is effectively a no-op. (We don't use WeakMap#delete
30
+ # because it was added in Ruby 3.3 and the matrix still includes 3.2.)
31
+ #
32
+ # The registry is read in the CHILD only (qfg-lv4n.1) — the hook does
33
+ # nothing on the parent side, so no lock is taken across the syscall.
32
34
  @instances = ObjectSpace::WeakMap.new
33
35
  @instances_mutex = Mutex.new
34
36
 
@@ -43,8 +45,7 @@ module Quonfig
43
45
  end
44
46
  end
45
47
 
46
- attr_reader :options, :resolver, :store, :evaluator, :instance_hash,
47
- :config_loader, :telemetry_reporter
48
+ attr_reader :options, :instance_hash, :telemetry_reporter
48
49
 
49
50
  def initialize(options = nil, store: nil, **option_kwargs)
50
51
  @options =
@@ -82,6 +83,25 @@ module Quonfig
82
83
  @sse_ever_connected = false
83
84
  @fallback_engage_timer = nil
84
85
  @sse_terminal_failure = false
86
+ # The process that owns this client's threads, sockets, and store.
87
+ # Re-stamped when a child takes ownership in #rebuild_in_child!. A pid
88
+ # mismatch is PROOF that we are looking at a fork(2) child, which is
89
+ # what makes #owned_by_this_process? exact. See that method for why
90
+ # thread liveness could not answer the question.
91
+ @owner_pid = Process.pid
92
+ # Post-fork lazy re-initialization (qfg-lv4n.1). Set by
93
+ # +after_fork_in_child+; cleared by the first use of the client in the
94
+ # child. See #ensure_initialized_after_fork.
95
+ @fork_rebuild_pending = false
96
+ @fork_rebuild_mutex = Mutex.new
97
+ # The thread currently running the rebuild, so a re-entrant read (a
98
+ # SemanticLoggerFilter or stdlib formatter that calls +get+ from inside
99
+ # the rebuild's own logging) does not deadlock on the non-reentrant
100
+ # Mutex above.
101
+ @fork_rebuild_owner = nil
102
+ # Sticky init error under +on_init_failure: :raise+ (see
103
+ # #raise_sticky_fork_init_error).
104
+ @fork_rebuild_error = nil
85
105
 
86
106
  # If the caller injected a store, we're in test/bootstrap mode; skip I/O.
87
107
  return if store
@@ -103,6 +123,7 @@ module Quonfig
103
123
  # ---- Lookup --------------------------------------------------------
104
124
 
105
125
  def get(key, default = NO_DEFAULT_PROVIDED, jit_context = NO_DEFAULT_PROVIDED)
126
+ ensure_initialized_after_fork
106
127
  ctx = build_context(jit_context)
107
128
  record_context_for_telemetry(ctx)
108
129
  result =
@@ -186,10 +207,12 @@ module Quonfig
186
207
  end
187
208
 
188
209
  def defined?(key)
210
+ ensure_initialized_after_fork
189
211
  !@store.get(key).nil?
190
212
  end
191
213
 
192
214
  def keys
215
+ ensure_initialized_after_fork
193
216
  @store.keys
194
217
  end
195
218
 
@@ -312,51 +335,117 @@ module Quonfig
312
335
  end
313
336
 
314
337
  def stop
338
+ # Order matters (qfg-lv4n.1 D5). The flag goes up BEFORE we queue for
339
+ # the rebuild lock, so a post-fork rebuild already in flight sees it and
340
+ # skips starting an update channel and a telemetry reporter at all —
341
+ # otherwise it builds an SSE worker after we have finished tearing down
342
+ # and nothing is left holding a reference to close it.
315
343
  @stopped = true
316
- tear_down_threaded_components!
344
+ # A child that never used the client must be able to stop it without
345
+ # paying for a re-initialization it never asked for.
346
+ @fork_rebuild_pending = false
347
+ @fork_rebuild_error = nil
348
+
349
+ # ...and the teardown itself is serialized against the rebuild, so it
350
+ # can never interleave with component construction. Re-entrancy: if the
351
+ # rebuild is what called `stop` (a customer on_update/logger hook), this
352
+ # thread already holds the lock.
353
+ if @fork_rebuild_owner == Thread.current
354
+ tear_down_threaded_components!
355
+ else
356
+ @fork_rebuild_mutex.synchronize { tear_down_threaded_components! }
357
+ end
317
358
  end
318
359
 
319
- # qfg-ryov: pre-fork hook. Close the SSE worker, polling supervisor,
320
- # telemetry reporter, and any fallback-engage timer. Idempotent calling
321
- # twice is safe. Does NOT set @stopped: the client is still expected to
322
- # be usable post-fork via after_fork_in_child.
360
+ # @deprecated Since 1.4.0 the +Process._fork+ hook NO LONGER CALLS THIS.
361
+ # A fork must not disturb the process that forked: the parent keeps its
362
+ # SSE stream, its poller, and its telemetry reporter, and keeps serving
363
+ # live config (qfg-lv4n.1). This method is retained for semver and for
364
+ # the Ruby 3.0 manual-wiring path, where a customer who genuinely wants
365
+ # the parent torn down before a fork can still call it. Prefer +stop+
366
+ # if you want the client dead.
323
367
  #
324
- # Why this matters: Ruby threads do not survive fork(2). If we let the
325
- # child inherit a live Net::HTTP socket, both processes read from the
326
- # same fd and corrupt each other's bytes. Closing in the parent before
327
- # fork is the only safe shape.
368
+ # Closes the SSE worker, polling supervisor, telemetry reporter, datadir
369
+ # watcher, and any fallback-engage timer. Idempotent. Does NOT set
370
+ # +@stopped+, so +after_fork_in_child+ can still rebuild.
328
371
  def before_fork_in_parent
329
372
  return if @stopped
330
373
 
331
374
  tear_down_threaded_components!
332
375
  end
333
376
 
334
- # qfg-ryov: post-fork (in child) hook. Re-establish whatever threaded
335
- # components the client had pre-fork. No-op if the client was already
336
- # stopped (the customer asked for it to be dead do not resurrect),
337
- # or if the client is in datadir mode (no threaded components to start).
377
+ # Post-fork hook, run IN THE CHILD ONLY (see Quonfig::ForkSafety).
378
+ #
379
+ # Ruby threads do not survive fork(2), so everything threaded the child
380
+ # inherited is a dead reference. The child drops those references and
381
+ # rebuilds from scratch — matching Reforge's +Reforge.fork+, which simply
382
+ # constructs a brand-new client and lets the inherited one be collected.
383
+ #
384
+ # Two things we deliberately do NOT do to the inherited objects:
385
+ #
386
+ # * **Never close the inherited SSE socket.** fork(2) duplicates the fd,
387
+ # so the child's copy points at the connection the PARENT is still
388
+ # streaming on. Closing a TLS socket writes a +close_notify+ alert onto
389
+ # that shared connection and kills the parent's stream. Dropping the
390
+ # reference leaves the parent's fd untouched.
391
+ # * **Never join an inherited thread.** The thread does not exist in the
392
+ # child, so a +join+/+stop+ that waits on it blocks forever (see
393
+ # LaunchDarkly ruby-server-sdk PR #430: "close blocks forever, because
394
+ # EventProcessor#stop waits for a dispatcher thread that does not
395
+ # exist").
396
+ #
397
+ # No-op if the client was already stopped — the customer asked for it to
398
+ # be dead, and a fork must not resurrect it.
399
+ #
400
+ # Also a no-op in the process that OWNS the client, i.e. the PARENT —
401
+ # decided by a pid stamp, not by whether anything looks alive. Releases
402
+ # 1.0-1.3 documented calling this in the parent as the workaround for the
403
+ # parent going dark after a fork; on 1.4.0+ such a call would orphan the
404
+ # parent's live components and zero its store, so it is ignored (one
405
+ # debug line). See #owned_by_this_process?.
406
+ #
407
+ # The hook does NO I/O: no fetch, no socket, no thread. It throws away
408
+ # everything the child inherited — including the parent's config snapshot
409
+ # — and arms a flag. The child re-initializes on its FIRST use of the
410
+ # client (see #ensure_initialized_after_fork), exactly like a newly
411
+ # constructed client would. A child that never uses the client, which is
412
+ # most of them in a `Parallel.map` batch, costs nothing at all.
338
413
  def after_fork_in_child
339
414
  return if @stopped
415
+ return if owned_by_this_process?
340
416
 
341
- if @options.datadir
342
- start_datadir_watcher if @options.data_dir_auto_reload
343
- return
344
- end
417
+ # The inherited Mutexes may be held by threads that no longer exist.
418
+ # Only this thread exists in a fresh child, so swapping them is safe.
419
+ @state_mutex = Mutex.new
420
+ @fork_rebuild_mutex = Mutex.new
421
+ @fork_rebuild_owner = nil
422
+ @fork_rebuild_error = nil
423
+ drop_inherited_threaded_components!
345
424
 
346
- return if @config_loader.nil? # never finished network init (e.g. invalid key)
425
+ # SSE state machine carries flags that describe the PARENT's session
426
+ # (it had connected, it had errored, ...). None of them apply here.
427
+ @sse_state = :idle
428
+ @sse_ever_connected = false
429
+ @sse_terminal_failure = false
430
+ @sse_error_callback = nil
347
431
 
348
- # SSE state machine carries flags that no longer apply in the child
349
- # (the parent had connected, the parent had errored, etc.). Reset.
350
- @state_mutex.synchronize do
351
- @sse_state = :idle
352
- @sse_ever_connected = false
353
- @sse_terminal_failure = false
354
- end
432
+ # A client that never finished network init has nothing to rebuild.
433
+ return if @config_loader.nil? && !@options.datadir
355
434
 
356
- sse_started = @options.enable_sse && start_sse
357
- start_polling if @options.fallback_poll_enabled && !sse_started
435
+ # A brand-new, EMPTY store. The child must not evaluate from whatever
436
+ # snapshot the parent happened to hold at the instant of the fork: it
437
+ # fetches (or loads) its own on first use.
438
+ reset_store_in_child!
358
439
 
359
- restart_telemetry_in_child
440
+ # Fresh aggregators. The parent flushes its own copy; a child that
441
+ # flushed inherited data would double-report it. The reporter is BUILT
442
+ # here (so the child's config loader points at the child's failover
443
+ # aggregator) but NOT started — starting it is I/O, and that waits for
444
+ # first use.
445
+ rebuild_aggregators_in_child!
446
+
447
+ @forked_in_pid = Process.pid
448
+ @fork_rebuild_pending = true
360
449
  end
361
450
 
362
451
  # quonfig_sdk_worker_restart_total counter (Tier 1 supervisor contract).
@@ -409,7 +498,17 @@ module Quonfig
409
498
  def connection_state
410
499
  @state_mutex.synchronize do
411
500
  next :disconnected if @stopped
501
+ # Forked, not yet used: nothing has been fetched and nothing is
502
+ # running. Saying so is the honest answer, and a diagnostic must not
503
+ # be what triggers a blocking fetch.
504
+ next :initializing if @fork_rebuild_pending
412
505
  next :falling_back if @poll_supervisor&.alive?
506
+ # Liveness beats the stored flag (qfg-lv4n.1). A client whose SSE
507
+ # session was torn down keeps a stale @sse_state; answering
508
+ # :connected off that flag is how a dark client reported healthy for
509
+ # 13 days. If this client is supposed to have a live SSE worker and
510
+ # does not, it is disconnected — whatever the flag says.
511
+ next :disconnected if sse_channel_expected? && !sse_worker_alive?
413
512
  next :connected if @sse_state == :connected
414
513
  next :disconnected if @sse_state == :error
415
514
 
@@ -461,7 +560,65 @@ module Quonfig
461
560
  sse.failed_over_to_secondary?
462
561
  end
463
562
 
563
+ # ---- Component readers ---------------------------------------------
564
+ #
565
+ # Public since 1.0 and kept public for semver. Each one routes through
566
+ # the post-fork chokepoint: in a forked child that has not been used yet
567
+ # the raw components read an EMPTY store (+store.get+ answered nil,
568
+ # +resolver.get+ raised MissingDefaultError), so handing them back
569
+ # without re-initializing is handing back a component that lies
570
+ # (qfg-lv4n.1 D6).
571
+
572
+ # @return [Quonfig::ConfigStore] the store backing this client.
573
+ # @note In a forked child, reading this triggers the lazy post-fork
574
+ # re-initialization (see #after_fork_in_child) — it can block on the
575
+ # child's own config fetch.
576
+ def store
577
+ ensure_initialized_after_fork
578
+ @store
579
+ end
580
+
581
+ # @return [Quonfig::Resolver]
582
+ # @note (see #store)
583
+ def resolver
584
+ ensure_initialized_after_fork
585
+ @resolver
586
+ end
587
+
588
+ # @return [Quonfig::Evaluator]
589
+ # @note (see #store)
590
+ def evaluator
591
+ ensure_initialized_after_fork
592
+ @evaluator
593
+ end
594
+
595
+ # @return [Quonfig::ConfigLoader, nil] nil in datadir mode.
596
+ # @note (see #store)
597
+ def config_loader
598
+ ensure_initialized_after_fork
599
+ @config_loader
600
+ end
601
+
602
+ # A client to use in a forked child.
603
+ #
604
+ # On Ruby 3.1+ the +Process._fork+ hook has already prepared THIS client
605
+ # in the child by the time any user code runs there (inherited threads
606
+ # and store dropped, re-initialization armed for first use). A call here
607
+ # in that child — the +on_worker_boot { Quonfig.fork }+ line the 1.0–1.3
608
+ # README taught — therefore returns +self+: the hook already did what the
609
+ # caller is asking for. Building a second client instead would discard
610
+ # the prepared one and pay an eager second fetch, or, after first use,
611
+ # leave the worker holding two live SSE streams and two reporters with
612
+ # the first pair orphaned where +stop+ can never reach it (qfg-4t5o).
613
+ #
614
+ # Everywhere else — the owning process, Ruby 3.0 where there is no hook,
615
+ # a client that was +stop+ped before the fork — this builds a fresh
616
+ # client, which is the Ruby 3.0 manual-wiring path. The old client is
617
+ # never stopped: on 3.0 it is the inherited one, and stopping it would
618
+ # close the inherited socket and tear down the PARENT's stream.
464
619
  def fork
620
+ return self if @forked_in_pid == Process.pid
621
+
465
622
  self.class.new(@options.for_fork)
466
623
  end
467
624
 
@@ -471,10 +628,73 @@ module Quonfig
471
628
 
472
629
  private
473
630
 
474
- # Close every threaded component and drop its reference. Used by both
475
- # +stop+ (where @stopped is also flipped) and +before_fork_in_parent+
476
- # (where @stopped is left alone so the child can restart).
631
+ # True when THIS process is the one that owns the client — i.e. we are
632
+ # the parent, not a fork(2) child.
633
+ #
634
+ # The answer is a pid comparison against the stamp taken when the client
635
+ # was constructed (and re-taken when a child rebuilds it). A pid mismatch
636
+ # is PROOF of a fork child; a match is proof that nobody forked.
637
+ #
638
+ # It deliberately does NOT ask whether any component looks alive, which
639
+ # is what 1.4.0 shipped and what got this wrong at both ends:
640
+ #
641
+ # * **False negative in a real child.** +on_update+ runs on the SSE worker
642
+ # thread, so a customer who forks from that callback forks ON it — and
643
+ # the inherited +@worker.alive?+ is therefore true in the child. The
644
+ # child was classified as the parent, ignored the hook, served the
645
+ # parent's snapshot forever and reported +:connected+ (qfg-lv4n.1 E1).
646
+ # * **False positive in a real parent.** A datadir client with
647
+ # auto-reload off and no SDK key has no threads and no reporter at all,
648
+ # so the guard let a parent-side call through and it wiped the live
649
+ # store (qfg-lv4n.1 E4/D4).
650
+ #
651
+ # The parent case is what makes a stray +after_fork_in_child+ call a
652
+ # no-op. Releases 1.0-1.3 documented exactly that call as the workaround
653
+ # for the parent-keeps-evaluating topology, and that code is still out
654
+ # there: on 1.4.0+ it would orphan the live SSE worker and its stream,
655
+ # zero the store, and stop the owner's telemetry reporter.
656
+ def owned_by_this_process?
657
+ return false unless @owner_pid == Process.pid
658
+
659
+ LOG.debug '[quonfig] after_fork_in_child called in the process that OWNS the client ' \
660
+ "(pid=#{Process.pid}); ignoring. Since 1.4.0 a fork never touches the " \
661
+ 'process that forked, and the child-side rebuild is automatic on Ruby 3.1+.'
662
+ true
663
+ end
664
+
665
+ # True when this client is a network-mode client that asked for SSE, i.e.
666
+ # one that is SUPPOSED to be holding a live stream. Datadir clients and
667
+ # store-injected (test/bootstrap) clients never are, so their
668
+ # +connection_state+ keeps deriving from envelope installs alone.
669
+ def sse_channel_expected?
670
+ return false if @options.datadir
671
+ return false unless @options.enable_sse
672
+
673
+ !@config_loader.nil?
674
+ end
675
+
676
+ # Is there an SSE worker thread actually running right now? Note this
677
+ # stays true across a reconnect: the worker owns the retry loop, so a
678
+ # blip does not read as "no channel".
679
+ def sse_worker_alive?
680
+ sse = @sse_client
681
+ return false if sse.nil?
682
+ return true unless sse.respond_to?(:alive?)
683
+
684
+ sse.alive?
685
+ end
686
+
687
+ # Close every threaded component and drop its reference. Used by +stop+
688
+ # (where @stopped is also flipped) and by the deprecated manual
689
+ # +before_fork_in_parent+ (where @stopped is left alone). NOT reachable
690
+ # from the fork hook any more — a fork never touches the process that
691
+ # forked (qfg-lv4n.1).
477
692
  def tear_down_threaded_components!
693
+ # The SSE state machine describes a session that no longer exists.
694
+ # Leaving @sse_state == :connected behind is how `connection_state`
695
+ # came to answer :connected for a client with nothing alive.
696
+ @state_mutex.synchronize { @sse_state = :idle }
697
+
478
698
  begin
479
699
  @sse_client&.close
480
700
  rescue StandardError => e
@@ -506,11 +726,233 @@ module Quonfig
506
726
  @datadir_watcher = nil
507
727
  end
508
728
 
509
- # Rebuild the telemetry reporter in the child after fork. Mirrors the
510
- # original initialize_telemetry path fresh aggregators, fresh reporter.
511
- def restart_telemetry_in_child
729
+ # Drop every inherited threaded component WITHOUT closing, stopping, or
730
+ # joining it. See the comment on +after_fork_in_child+ for why touching
731
+ # these objects in the child is actively harmful (shared socket fds,
732
+ # threads that do not exist). Reforge, LaunchDarkly, dd-trace-rb,
733
+ # redis-client and connection_pool all do exactly this.
734
+ def drop_inherited_threaded_components!
735
+ inherited_reporter = @telemetry_reporter
736
+
737
+ @sse_client = nil
738
+ @poll_supervisor = nil
512
739
  @telemetry_reporter = nil
513
- initialize_telemetry
740
+ @datadir_watcher = nil
741
+ @fallback_engage_timer = nil
742
+
743
+ # Dropping our reference is not enough for the reporter: its
744
+ # `Kernel.at_exit { final_drain_on_exit }` closure is process-wide, it
745
+ # was copied by fork(2), and it still holds a full copy of the PARENT's
746
+ # un-flushed telemetry window. The reporter's own owner-pid guard is
747
+ # what makes that closure inert (see TelemetryReporter#start); this
748
+ # additionally makes the copied window unreachable. Neither stops,
749
+ # closes, nor joins anything.
750
+ begin
751
+ inherited_reporter&.discard_inherited!
752
+ rescue StandardError => e
753
+ LOG.debug "Error discarding inherited telemetry reporter: #{e.message}"
754
+ end
755
+ end
756
+
757
+ # Lazy post-fork re-initialization. Called from every read entry point
758
+ # (+get+, +evaluate_details+, +defined?+, +keys+) — the flag read is a
759
+ # plain boolean, so the steady-state cost is one comparison per lookup.
760
+ #
761
+ # The first caller in the child does what +Client.new+ does: its own
762
+ # config fetch under the configured init timeout and +on_init_failure+
763
+ # policy, then its own SSE stream (or fallback poller) and its own
764
+ # telemetry reporter. It BLOCKS, so that first lookup already reflects
765
+ # the child's own current config.
766
+ #
767
+ # +connection_state+ deliberately does NOT trigger this: a diagnostic
768
+ # must never open a socket. It reports +:initializing+ while a rebuild is
769
+ # pending, which is exactly what the client is.
770
+ def ensure_initialized_after_fork
771
+ # Hot path: two ivar reads and no lock. Both are falsy for every client
772
+ # that has never been through a fork.
773
+ return unless @fork_rebuild_pending || @fork_rebuild_error
774
+ # Re-entrancy guard: a customer logger (SemanticLoggerFilter, stdlib
775
+ # formatter) that evaluates a config from inside the rebuild would
776
+ # otherwise deadlock on the non-reentrant Mutex. Such a call sees the
777
+ # half-built client, which is the same thing Client.new gives a logger
778
+ # that fires during construction.
779
+ return if @fork_rebuild_owner == Thread.current
780
+
781
+ run_pending_child_rebuild if @fork_rebuild_pending
782
+ raise_sticky_fork_init_error if @fork_rebuild_error
783
+ end
784
+
785
+ # Run the rebuild under the lock, or block until whoever is running it is
786
+ # done. The flag stays TRUE for the whole rebuild, which is what makes
787
+ # every other first-use caller take the mutex and WAIT rather than sail
788
+ # past on the unlocked fast path and evaluate against the empty store.
789
+ def run_pending_child_rebuild
790
+ @fork_rebuild_mutex.synchronize do
791
+ # Lost the race: the winner already rebuilt (or `stop` disarmed us).
792
+ return unless @fork_rebuild_pending
793
+ return if @stopped
794
+
795
+ @fork_rebuild_owner = Thread.current
796
+ begin
797
+ rebuild_in_child!
798
+ rescue StandardError => e
799
+ # Handled: the child gets whatever healing path its mode allows, so
800
+ # the next lookup must not re-run the blocking fetch. (The datadir
801
+ # recovery path may deliberately re-arm — see
802
+ # #recover_datadir_child_after_failed_rebuild.)
803
+ @fork_rebuild_pending = false
804
+ handle_child_rebuild_failure(e)
805
+ ensure
806
+ @fork_rebuild_owner = nil
807
+ # #rebuild_in_child! disarms the flag itself the moment the child
808
+ # has a live path to config. Anything that escapes before that —
809
+ # including a non-StandardError such as rack-timeout's
810
+ # RequestTimeoutException, Ruby 3.3's Timeout::ExitException, or a
811
+ # Thread#kill, none of which the rescue above can see — leaves the
812
+ # flag armed so the NEXT call retries instead of leaving the child
813
+ # dark forever (qfg-lv4n.1 D2).
814
+ @fork_rebuild_pending = false if @stopped
815
+ end
816
+ end
817
+ end
818
+
819
+ # Under +on_init_failure: :raise+ a failed rebuild raises out of the call
820
+ # that triggered it, exactly as +Client.new+ would — and keeps raising on
821
+ # subsequent calls (without re-fetching) until the update channel heals
822
+ # the store. Under +:return+ nothing is stored here and this never fires.
823
+ def raise_sticky_fork_init_error
824
+ err = @fork_rebuild_error
825
+ return if err.nil?
826
+
827
+ if ready?
828
+ # The SSE stream (or the poller) installed an envelope: the client is
829
+ # serving real config again, so the init failure is history.
830
+ @fork_rebuild_error = nil
831
+ return
832
+ end
833
+
834
+ raise err
835
+ end
836
+
837
+ # A rebuild that raised. Log it, give the child whatever healing path its
838
+ # mode has, and honor +on_init_failure+.
839
+ def handle_child_rebuild_failure(err)
840
+ LOG.error "[quonfig] post-fork re-initialization failed: #{err.class}: #{err.message}"
841
+
842
+ if @options.datadir
843
+ recover_datadir_child_after_failed_rebuild
844
+ else
845
+ begin
846
+ start_update_channel if @sse_client.nil? && @poll_supervisor.nil?
847
+ rescue StandardError => e
848
+ LOG.error "[quonfig] post-fork update channel failed to start: #{e.class}: #{e.message}"
849
+ end
850
+ end
851
+
852
+ return unless @options.on_init_failure == Quonfig::Options::ON_INITIALIZATION_FAILURE::RAISE
853
+
854
+ # Parity with a fresh Client.new, which raises under :raise. Stored so
855
+ # later calls keep raising rather than re-running the fetch on every
856
+ # lookup.
857
+ @fork_rebuild_error = err
858
+ raise err
859
+ end
860
+
861
+ # A datadir client is configured OFFLINE: it has no config loader, so
862
+ # opening an SSE stream here dials the network on a customer who asked
863
+ # for none and then blows up on every envelope that arrives
864
+ # ("undefined method `apply_envelope' for nil"). The healing path for a
865
+ # datadir child is the filesystem: start the watcher if auto-reload is on
866
+ # so a repaired workspace is picked up, and otherwise re-arm the rebuild
867
+ # so the next use retries the load (qfg-lv4n.1 D3).
868
+ def recover_datadir_child_after_failed_rebuild
869
+ begin
870
+ start_datadir_watcher if @options.data_dir_auto_reload && @datadir_watcher.nil?
871
+ rescue StandardError => e
872
+ LOG.error "[quonfig] post-fork datadir watcher failed to start: #{e.class}: #{e.message}"
873
+ end
874
+
875
+ return unless @datadir_watcher.nil?
876
+
877
+ @fork_rebuild_pending = true
878
+ end
879
+
880
+ # The child's own re-initialization, run on first use. Mirrors what
881
+ # +Client.new+ does for this client's mode, and logs one info line so a
882
+ # customer grepping their logs can see the SDK noticed the fork.
883
+ def rebuild_in_child!
884
+ # This process is taking ownership of the client. Re-stamping here is
885
+ # what keeps #owned_by_this_process? exact for everything that follows:
886
+ # a manual +after_fork_in_child+ in THIS child is now correctly a
887
+ # no-op, and a grandchild forked from here is still detected by pid.
888
+ @owner_pid = Process.pid
889
+ components = []
890
+
891
+ if @options.datadir
892
+ load_datadir_into_store
893
+ components << 'datadir'
894
+ start_datadir_watcher if @options.data_dir_auto_reload
895
+ components << 'datadir-watcher' if @datadir_watcher
896
+ else
897
+ initialize_network_mode
898
+ components << 'config' if ready?
899
+ components << 'sse' if @sse_client
900
+ components << 'polling' if @poll_supervisor
901
+ end
902
+
903
+ # The child now has a live path to config (a stream/poller, or a loaded
904
+ # datadir). Disarm HERE, not in the caller: everything above is
905
+ # retryable and must stay armed if it is interrupted, and everything
906
+ # below must never re-run the fetch or dial a second stream.
907
+ @fork_rebuild_pending = false
908
+
909
+ unless @stopped
910
+ @telemetry_reporter&.start
911
+ components << 'telemetry' if @telemetry_reporter
912
+ end
913
+
914
+ log_child_rebuild(components)
915
+ end
916
+
917
+ # A brand-new store (plus the evaluator, resolver, and config loader that
918
+ # read it) so the child starts from nothing and installs its own envelope.
919
+ # Two things this buys beyond "no stale config": the child's first
920
+ # envelope is ACCEPTED rather than dropped by the reject-older guard as
921
+ # same-generation, and a fork that lands mid-install can no longer hand
922
+ # the child a half-written store.
923
+ def reset_store_in_child!
924
+ @store = Quonfig::ConfigStore.new
925
+ @evaluator = Quonfig::Evaluator.new(@store, env_id: @options.environment)
926
+ @resolver = Quonfig::Resolver.new(@store, @evaluator)
927
+ @last_successful_refresh = nil
928
+ return if @options.datadir
929
+
930
+ @config_loader = Quonfig::ConfigLoader.new(@store, @options, failover_aggregator: @failover_aggregator)
931
+ end
932
+
933
+ # Replace every aggregator with a fresh, empty one so the child never
934
+ # re-reports data the parent collected (and is still going to flush from
935
+ # its own copy). Mirrors what a brand-new Client.new would allocate.
936
+ def rebuild_aggregators_in_child!
937
+ @failover_aggregator = Quonfig::Telemetry::FailoverAggregator.new
938
+ # The ConfigLoader records hedge/guard/resolved-from at its failover
939
+ # call sites, so it has to point at the child's aggregator too — the
940
+ # inherited one is now the parent's private object.
941
+ @config_loader.failover_aggregator = @failover_aggregator if @config_loader.respond_to?(:failover_aggregator=)
942
+
943
+ # initialize_telemetry allocates fresh context/example/summaries
944
+ # aggregators and a fresh reporter. It is NOT started here: starting the
945
+ # reporter is I/O and a thread, and both wait for the child's first use.
946
+ @telemetry_reporter = nil
947
+ initialize_telemetry(start: false)
948
+ end
949
+
950
+ # One line, at info, so a customer can see in their logs that the SDK
951
+ # noticed the fork and rebuilt. Deliberately not a warning: forking is
952
+ # normal and expected.
953
+ def log_child_rebuild(components)
954
+ list = components.empty? ? 'none' : components.join(',')
955
+ LOG.info "[quonfig] re-initialized after fork pid=#{Process.pid} components=#{list}"
514
956
  end
515
957
 
516
958
  # Stamp +last_successful_refresh+ at install time. Called by every code
@@ -668,7 +1110,7 @@ module Quonfig
668
1110
  # Construct and start the telemetry reporter if the options permit it.
669
1111
  # The reporter runs on a background thread and periodically POSTs
670
1112
  # context-shape and example-context batches to +telemetry_destination+.
671
- def initialize_telemetry
1113
+ def initialize_telemetry(start: true)
672
1114
  shape_aggregator = nil
673
1115
  example_aggregator = nil
674
1116
  summaries_aggregator = nil
@@ -704,6 +1146,7 @@ module Quonfig
704
1146
  )
705
1147
 
706
1148
  return unless @telemetry_reporter.enabled?
1149
+ return unless start
707
1150
 
708
1151
  @telemetry_reporter.start
709
1152
  rescue StandardError => e
@@ -826,15 +1269,32 @@ module Quonfig
826
1269
  warn_if_hedge_abort_exceeds_init_timeout
827
1270
  warn_if_explicit_api_urls_disables_failover
828
1271
 
829
- @config_loader = Quonfig::ConfigLoader.new(@store, @options, failover_aggregator: @failover_aggregator)
1272
+ # ||=: after a fork the child already built its loader over its fresh
1273
+ # store (see #reset_store_in_child!).
1274
+ @config_loader ||= Quonfig::ConfigLoader.new(@store, @options, failover_aggregator: @failover_aggregator)
830
1275
 
831
1276
  perform_initial_fetch
1277
+ start_update_channel
1278
+ end
832
1279
 
833
- sse_started = @options.enable_sse && start_sse
1280
+ # SSE if enabled and it comes up; otherwise the HTTP polling fallback.
1281
+ # Polling is a fallback: if SSE is off or failed to start, poll. This
1282
+ # avoids double-work when SSE is healthy but still refreshes the store in
1283
+ # environments that block SSE (corporate proxies, Lambda, etc.).
1284
+ def start_update_channel
1285
+ # A `stop` that raced the post-fork rebuild must win: never dial a
1286
+ # stream for a client the customer has already killed (qfg-lv4n.1).
1287
+ return if @stopped
1288
+ # Idempotent. `rebuild_in_child!` disarms @fork_rebuild_pending only
1289
+ # AFTER initialize_network_mode has already started the channel, so a
1290
+ # non-StandardError landing in that window (rack-timeout,
1291
+ # Timeout::ExitException, Thread#kill) leaves the flag armed WITH a
1292
+ # live stream. The retry re-runs initialize_network_mode; without this
1293
+ # guard it dialled a SECOND stream and overwrote @sse_client, orphaning
1294
+ # the first worker where `stop` could never reach it (qfg-lv4n.1 E2).
1295
+ return if sse_worker_alive? || @poll_supervisor&.alive?
834
1296
 
835
- # Polling is a fallback: if SSE is off or failed to start, poll. This
836
- # avoids double-work when SSE is healthy but still refreshes the store
837
- # in environments that block SSE (corporate proxies, Lambda, etc.).
1297
+ sse_started = @options.enable_sse && start_sse
838
1298
  start_polling if @options.enable_polling && !sse_started
839
1299
  end
840
1300
 
@@ -959,6 +1419,7 @@ module Quonfig
959
1419
  # Returns true if SSE started successfully, false otherwise. A false here
960
1420
  # signals the caller to fall back to polling.
961
1421
  def start_sse
1422
+ return false if @stopped
962
1423
  return false if @options.sse_api_urls.nil? || @options.sse_api_urls.empty?
963
1424
 
964
1425
  @sse_client = Quonfig::SSEConfigClient.new(
@@ -1143,6 +1604,7 @@ module Quonfig
1143
1604
  # caller's context, after coercing/checking +expected_type+. Never
1144
1605
  # raises; all exceptions become ERROR details.
1145
1606
  def evaluate_details(key, expected_type, context)
1607
+ ensure_initialized_after_fork
1146
1608
  jit = context == NO_DEFAULT_PROVIDED ? nil : context
1147
1609
  ctx = build_context(jit)
1148
1610
  record_context_for_telemetry(ctx)
@@ -1282,32 +1744,52 @@ module Quonfig
1282
1744
  end
1283
1745
  end
1284
1746
 
1285
- # qfg-ryov: hook into Process._fork so customers using Puma's clustered
1286
- # mode (or any preload/fork-worker server) don't have to wire
1287
- # +before_fork+/+on_worker_boot+ manually. Ruby 3.1+ routes every
1288
- # +Kernel#fork+/+Process.fork+ call through +Process._fork+, so a single
1289
- # prepend covers them all.
1747
+ # qfg-ryov / qfg-lv4n.1: hook into Process._fork so customers using Puma's
1748
+ # clustered mode (or any preload/fork-worker server, or a gem that forks
1749
+ # inside a job) don't have to wire +before_fork+/+on_worker_boot+ manually.
1750
+ # Ruby 3.1+ routes every +Kernel#fork+/+Process.fork+ call through
1751
+ # +Process._fork+, so a single prepend covers them all.
1290
1752
  #
1291
1753
  # Process._fork's contract:
1292
1754
  # - Called in the parent process before the fork syscall.
1293
1755
  # - Returns 0 in the child, child's pid in the parent.
1294
1756
  # - +super+ performs the actual fork.
1295
1757
  #
1296
- # The parent's view: SSE/polling/telemetry threads are torn down before
1297
- # the syscall so the child does not inherit a live Net::HTTP socket fd
1298
- # (which would corrupt both sides). The parent does NOT auto-restart
1299
- # that mirrors the Puma master use case where the master process no
1300
- # longer serves requests after spawning workers.
1758
+ # **The hook is child-only.** Nothing happens in the parent — not before
1759
+ # the syscall, not after it. A fork is somebody else's business; the
1760
+ # process that forked keeps its SSE stream, its poller, its telemetry
1761
+ # reporter, and its live config. This is Reforge's model (+Reforge.fork+
1762
+ # builds a new client in the child and never touches the old one) and
1763
+ # matches dd-trace-rb, redis-client and connection_pool, which all branch
1764
+ # on the child stage of +_fork+ only.
1765
+ #
1766
+ # It replaces the qfg-ryov shape, which tore the parent down before the
1767
+ # syscall on the theory that the child must not inherit a live socket fd.
1768
+ # That was wrong twice over: the child never touches the inherited fd (it
1769
+ # drops the reference — see Client#after_fork_in_child), and a Sidekiq
1770
+ # parent that forks a worker and keeps evaluating went dark for 13 days in
1771
+ # production.
1301
1772
  module ForkSafety
1302
1773
  def _fork
1303
- Quonfig::Client.each_instance(&:before_fork_in_parent)
1304
1774
  pid = super
1305
- Quonfig::Client.each_instance(&:after_fork_in_child) if pid.zero?
1775
+ if pid.zero?
1776
+ # Per-instance, not per-fan-out: a process can hold more than one
1777
+ # Client (a second workspace, a test harness, a gem that builds its
1778
+ # own). One of them failing to rebuild — thread exhaustion, a
1779
+ # customer logger that raises — must not cost every client behind it
1780
+ # in the registry its rebuild and leave the child silently dark.
1781
+ Quonfig::Client.each_instance do |client|
1782
+ client.after_fork_in_child
1783
+ rescue StandardError => e
1784
+ Quonfig::Client::LOG.error 'Quonfig fork rebuild failed for one client ' \
1785
+ "(continuing with the rest): #{e.class}: #{e.message}"
1786
+ end
1787
+ end
1306
1788
  pid
1307
1789
  rescue StandardError => e
1308
1790
  # Fork-hook failures must never break the customer's fork. Worst case
1309
- # the child inherits dead SSE threads (the pre-qfg-ryov behavior)
1310
- # bad, but recoverable. Crashing the fork itself is not.
1791
+ # the child holds dropped references and no live threads bad, but
1792
+ # recoverable. Crashing the fork itself is not.
1311
1793
  Quonfig::Client::LOG.error "Quonfig fork hook error: #{e.class}: #{e.message}"
1312
1794
  raise if pid.nil? # super never returned — propagate fork failures
1313
1795