From 82d3b93b94e9bf75fcc02c7c11a483931acfee3d Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:07:28 +0000 Subject: [PATCH 1/6] deps: update dependency flagsmith/sdk-spec to v0.9.0 --- .github/workflows/sdk-spec.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/sdk-spec.yml b/.github/workflows/sdk-spec.yml index 61b675e..4a2866c 100644 --- a/.github/workflows/sdk-spec.yml +++ b/.github/workflows/sdk-spec.yml @@ -11,8 +11,8 @@ permissions: jobs: sdk-spec: # Keep the ref in `uses:` and `spec-ref` in sync. - uses: Flagsmith/sdk-spec/.github/workflows/run-spec.yml@v0.7.1 + uses: Flagsmith/sdk-spec/.github/workflows/run-spec.yml@v0.9.0 with: - spec-ref: v0.7.1 + spec-ref: v0.9.0 language: elixir tags: core or events or local-evaluation From f2c693bde4aec1fa4c9417b3dcc9819688aed4f7 Mon Sep 17 00:00:00 2001 From: "flagsmith-engineering[bot]" <216534828+flagsmith-engineering[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:07:37 +0000 Subject: [PATCH 2/6] ci: Run the SDK spec for this SDK's capabilities Its entry in Flagsmith/sdk-spec's compatibility matrix at v0.9.0: `core events local-evaluation`. --- .github/workflows/sdk-spec.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/sdk-spec.yml b/.github/workflows/sdk-spec.yml index 4a2866c..bb978e9 100644 --- a/.github/workflows/sdk-spec.yml +++ b/.github/workflows/sdk-spec.yml @@ -15,4 +15,4 @@ jobs: with: spec-ref: v0.9.0 language: elixir - tags: core or events or local-evaluation + tags: core events local-evaluation From b6b19ed1d695c7e8f37af83371ce493bd8da53b9 Mon Sep 17 00:00:00 2001 From: "flagsmithsmith[bot]" <346993984+flagsmithsmith[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:01:06 +0000 Subject: [PATCH 3/6] feat: Retry event delivery and flush on close Implements the SDK spec v0.9.0 for events: - Event batches are sent up to 3 times, giving up on each attempt after 3 seconds and backing off from 1 second, doubling, with full jitter. Batches the events API rejects are dropped, as are those whose last attempt fails with a 500; others are kept for the next flush, ahead of events tracked since. A 401 or 403 stops event tracking. - A full buffer (1000 events) drops its oldest event. - `Flagsmith.Client.flush_events/1` sends the tracked events and returns once they have been delivered, dropped or kept. - `Flagsmith.Client.close/2` sends the buffered events within a timeout, and stops the client's events processor and poller. - Local evaluation now reads experiment metadata and variant keys from the environment document, so experiment flags evaluated locally carry their experiment and variant, and send exposures. Co-Authored-By: Claude Opus 5.5 --- lib/engine/mappers.ex | 1 + lib/flagsmith_client.ex | 86 ++++- lib/flagsmith_client_events_processor.ex | 180 ++++++++- lib/flagsmith_client_poller.ex | 11 + lib/flagsmith_engine.ex | 19 +- lib/schemas/environment_feature_state.ex | 7 +- ...environment_multivariate_feature_option.ex | 3 +- lib/schemas/flag.ex | 6 +- .../events_processor_supervisor.ex | 2 +- sdk-spec/steps.exs | 36 ++ test/flagsmith_events_test.exs | 341 +++++++++++++++++- 11 files changed, 639 insertions(+), 53 deletions(-) diff --git a/lib/engine/mappers.ex b/lib/engine/mappers.ex index 22d0656..4160bd2 100644 --- a/lib/engine/mappers.ex +++ b/lib/engine/mappers.ex @@ -128,6 +128,7 @@ defmodule Flagsmith.Engine.Mappers do defp map_variant(%Environment.MultivariateFeatureStateValue{} = value) do %{ "value" => value.multivariate_feature_option.value, + "key" => value.multivariate_feature_option.key, "weight" => value.percentage_allocation, "priority" => value.id || value.mv_fs_value_uuid } diff --git a/lib/flagsmith_client.ex b/lib/flagsmith_client.ex index bbe160b..ce21534 100644 --- a/lib/flagsmith_client.ex +++ b/lib/flagsmith_client.ex @@ -328,6 +328,50 @@ defmodule Flagsmith.Client do def track_exposure_event(opts, feature_name, event_opts) when is_list(opts), do: track_exposure_event(new(opts), feature_name, event_opts) + @doc """ + Sends the events tracked so far to Flagsmith without waiting for the flush interval, + and returns once each of them has been delivered, dropped, or kept for the next flush. + + Sending a batch of events is attempted up to 3 times, giving up on an attempt after + 3 seconds and backing off from 1 second, doubling, with full jitter. A batch the + events API rejects is dropped, and one it keeps failing is kept for the next flush, + ahead of the events tracked since. An events API refusing the environment key stops + event tracking. Up to 1000 events are buffered: when full, the oldest one is dropped. + """ + @spec flush_events(Configuration.t() | Keyword.t()) :: :ok | :noop | {:error, term()} + def flush_events(%Configuration{enable_events: false}), do: {:error, :events_disabled} + + def flush_events(%Configuration{environment_key: environment_key}), + do: Events.Processor.flush(environment_key) + + def flush_events(opts) when is_list(opts), do: flush_events(new(opts)) + + @doc """ + Closes the client: sends its buffered events, waiting for at most `timeout` + milliseconds (5 seconds by default), and stops the processes running for its + environment key, polling the environment and sending events. Events not sent by + then are dropped. + + Using the client again starts them again. + """ + @spec close(Configuration.t() | Keyword.t(), timeout :: non_neg_integer()) :: + :ok | :noop | {:error, term()} + def close(configuration_or_opts, timeout \\ 5000) + + def close( + %Configuration{ + environment_key: environment_key, + enable_local_evaluation: local?, + enable_events: events? + }, + timeout + ) do + if local?, do: Flagsmith.Client.Poller.stop(environment_key) + if events?, do: Events.Processor.close(environment_key, timeout), else: :noop + end + + def close(opts, timeout) when is_list(opts), do: close(new(opts), timeout) + @doc """ Return all flags from an environment as a list. If a `t:Flagsmith.Schemas.Environment.t/0` is passed instead of a @@ -482,23 +526,39 @@ defmodule Flagsmith.Client do do: analytics_track(new(opts), tracking) @doc false - # Submits a batch of events to the Flagsmith events API. - @spec events_track(Configuration.t(), list(Events.Processor.event())) :: - {:ok, term()} | {:error, term()} - def events_track(%Configuration{events_api_url: events_api_url} = config, events) do - case Tesla.post( - http_client(%{config | api_url: events_api_url}), - @api_paths.events, - %{events: events} + # Submits a batch of events to the Flagsmith events API, once, giving up on it after + # `timeout` milliseconds. Returns the response's status, or the reason no response was + # received; retrying is up to the caller. + @spec events_track(Configuration.t(), list(Events.Processor.event()), pos_integer()) :: + {:ok, Tesla.Env.status()} | {:error, term()} + def events_track(%Configuration{} = config, events, timeout) do + case Tesla.post(events_http_client(config, timeout), @api_paths.events, %{events: events}, + opts: [adapter: [timeout: timeout]] ) do - {:ok, %{status: status, body: body}} when status >= 200 and status < 300 -> - {:ok, body} - - error_resp -> - return_error(error_resp) + {:ok, %Tesla.Env{status: status}} -> {:ok, status} + {:error, _} = error -> error end end + @spec events_http_client(Configuration.t(), pos_integer()) :: Tesla.Client.t() + defp events_http_client( + %Configuration{ + environment_key: environment_key, + events_api_url: events_api_url, + custom_headers: custom_headers + }, + timeout + ) do + Tesla.client([ + base_url_middleware(events_api_url), + auth_middleware(environment_key), + user_agent_middleware(), + Tesla.Middleware.JSON, + {Tesla.Middleware.Headers, custom_headers}, + {Tesla.Middleware.Timeout, timeout: timeout} + ]) + end + @doc false # Given an `t:Flagsmith.Schemas.Environment.t/0` or a list composed of # `t:Flagsmith.Schemas.Environment.FeatureState.t/0` or diff --git a/lib/flagsmith_client_events_processor.ex b/lib/flagsmith_client_events_processor.ex index b2c8bfa..cf26049 100644 --- a/lib/flagsmith_client_events_processor.ex +++ b/lib/flagsmith_client_events_processor.ex @@ -19,11 +19,23 @@ defmodule Flagsmith.Client.Events.Processor do @flag_exposure_event "$flag_exposure" @max_buffered_events 1000 + @max_attempts 3 + @request_timeout_milliseconds 3000 + @retry_base_milliseconds if(Mix.env() == :test, do: 20, else: 1000) + @default_close_timeout_milliseconds 5000 + # Statuses that a later attempt may not get, besides server errors. + @retried_statuses [408, 429] + # Statuses meaning the events API refuses the environment key. + @refused_statuses [401, 403] @enforce_keys [:configuration] defstruct [ :configuration, - buffer: [], + buffer: :queue.new(), + buffered: 0, + # Whether events were tracked since the last attempt to send the buffer. + unsent: false, + refused: false, exposure_keys: MapSet.new() ] @@ -60,16 +72,46 @@ defmodule Flagsmith.Client.Events.Processor do end @doc """ - Sends every buffered event to the Flagsmith events API, returning once done. + Sends the events tracked so far to the Flagsmith events API, retries included, and + returns once each of them has been delivered, dropped, or kept for the next flush. + Returns `:noop` when there is nothing to send, including when the buffer only holds + events already kept from a failed flush, which the next timed flush sends. """ @spec flush(environment_key()) :: :ok | :noop | {:error, term()} def flush(environment_key) do case whereis(environment_key) do - pid when is_pid(pid) -> GenServer.call(pid, :flush) + pid when is_pid(pid) -> GenServer.call(pid, :flush, :infinity) :undefined -> :noop end end + @doc """ + Sends the buffered events, and stops the processor, waiting for at most `timeout` + milliseconds. Events not sent by then are dropped. + """ + @spec close(environment_key(), non_neg_integer()) :: :ok | :noop | {:error, term()} + def close(environment_key, timeout \\ @default_close_timeout_milliseconds) do + case whereis(environment_key) do + pid when is_pid(pid) -> + deadline = System.monotonic_time(:millisecond) + timeout + + try do + GenServer.call(pid, {:close, deadline}, timeout) + catch + # The processor is still sending a batch: it stops once done, past the deadline. + :exit, {:timeout, _} -> + Logger.warning("Gave up sending events after #{timeout} milliseconds while closing") + {:error, :timeout} + + :exit, {reason, _} when reason in [:noproc, :normal, :shutdown] -> + :noop + end + + :undefined -> + :noop + end + end + @doc false @spec processor_id(environment_key()) :: processor_identifier() def processor_id(environment_key), do: {__MODULE__, environment_key} @@ -113,6 +155,11 @@ defmodule Flagsmith.Client.Events.Processor do end @impl GenServer + def handle_cast({:track, event}, %__MODULE__{refused: true} = data) do + Logger.debug("Not tracking #{event.event} event: the events API refused the environment key") + {:noreply, data} + end + def handle_cast({:track, event}, %__MODULE__{} = data) do case exposure_key(event) do nil -> @@ -137,14 +184,22 @@ defmodule Flagsmith.Client.Events.Processor do end @impl GenServer + def handle_call(:flush, _from, %__MODULE__{unsent: false} = data), + do: {:reply, :noop, data} + def handle_call(:flush, _from, %__MODULE__{} = data) do - {result, data} = do_flush(data) + {result, data} = do_flush(data, :infinity) {:reply, result, data} end + def handle_call({:close, deadline}, _from, %__MODULE__{} = data) do + {result, _data} = do_flush(data, deadline) + {:stop, :normal, result, %{data | buffer: :queue.new(), buffered: 0}} + end + @impl GenServer def handle_info(:flush, %__MODULE__{configuration: config} = data) do - {_, data} = do_flush(data) + {_, data} = do_flush(data, :infinity) schedule_flush(config) {:noreply, data} end @@ -152,41 +207,126 @@ defmodule Flagsmith.Client.Events.Processor do def handle_info(_, data), do: {:noreply, data} @impl GenServer - def terminate(_reason, %__MODULE__{} = data), do: do_flush(data) + def terminate(_reason, %__MODULE__{} = data) do + do_flush(data, System.monotonic_time(:millisecond) + @default_close_timeout_milliseconds) + end defp exposure_key(%{event: @flag_exposure_event} = event), do: {event.feature_name, event.identifier, event.value} defp exposure_key(_), do: nil - defp buffer(%__MODULE__{buffer: buffer} = data, event) do - data = %{data | buffer: [event | buffer]} + # A full buffer drops its oldest event for the new one. Filling it up sends it + # without waiting for the flush interval. + defp buffer(%__MODULE__{buffered: @max_buffered_events} = data, event) do + {{:value, dropped}, buffer} = :queue.out(data.buffer) + Logger.warning("Event buffer is full, dropping the oldest #{dropped.event} event") + %{data | buffer: :queue.in(event, buffer), unsent: true} + end - case length(data.buffer) >= @max_buffered_events do - true -> elem(do_flush(data), 1) - false -> data + defp buffer(%__MODULE__{} = data, event) do + data = %{ + data + | buffer: :queue.in(event, data.buffer), + buffered: data.buffered + 1, + unsent: true + } + + case data.buffered do + @max_buffered_events -> elem(do_flush(data, :infinity), 1) + _ -> data end end - defp do_flush(%__MODULE__{buffer: []} = data), do: {:noop, data} + defp do_flush(%__MODULE__{buffered: 0} = data, _deadline), do: {:noop, data} + + defp do_flush(%__MODULE__{configuration: config} = data, deadline) do + events = :queue.to_list(data.buffer) + sent = %{data | buffer: :queue.new(), buffered: 0, unsent: false, exposure_keys: MapSet.new()} + + case deliver(config, events, deadline, 1) do + :delivered -> + {:ok, sent} - defp do_flush(%__MODULE__{configuration: config, buffer: buffer} = data) do - events = Enum.reverse(buffer) + {:dropped, reason} -> + {{:error, reason}, sent} - case Flagsmith.Client.events_track(config, events) do - {:ok, _} -> - {:ok, %{data | buffer: [], exposure_keys: MapSet.new()}} + {:refused, reason} -> + Logger.error("The events API refused the environment key, stopping event tracking") + {{:error, reason}, %{sent | refused: true}} - {:error, reason} = error -> - Logger.warning("Failed to send events to Flagsmith, keeping them to retry", + {:kept, reason} -> + Logger.warning("Failed to send events to Flagsmith, keeping them for the next flush", reason: inspect(reason), events: length(events) ) - {error, %{data | buffer: Enum.take(buffer, @max_buffered_events)}} + {{:error, reason}, %{data | unsent: false}} end end + # Sends a batch up to @max_attempts times, backing off with full jitter between + # attempts, until `deadline`. Returns what became of the batch: delivered, dropped + # (rejected by the events API, or failed with a 500 on its last attempt), refused + # (the events API refuses the environment key), or kept for the next flush. + defp deliver(config, events, deadline, attempt) do + case remaining(deadline) do + 0 -> + {:kept, :timeout} + + remaining -> + config + |> Flagsmith.Client.events_track(events, min(remaining, @request_timeout_milliseconds)) + |> handle_attempt(config, events, deadline, attempt) + end + end + + defp handle_attempt({:ok, status}, _, _, _, _) when status in 200..299, do: :delivered + + defp handle_attempt({:ok, status}, _, _, _, _) when status in @refused_statuses, + do: {:refused, {:status, status}} + + defp handle_attempt({:ok, status}, _, events, _, _) + when status < 500 and status not in @retried_statuses do + Logger.warning( + "The events API rejected #{length(events)} events with #{status}, dropping them" + ) + + {:dropped, {:status, status}} + end + + defp handle_attempt({:ok, 500}, _, events, _, @max_attempts) do + Logger.warning("The events API failed #{length(events)} events with 500, dropping them") + {:dropped, {:status, 500}} + end + + defp handle_attempt(result, _, _, _, @max_attempts), do: {:kept, failure(result)} + + defp handle_attempt(result, config, events, deadline, attempt) do + Logger.warning( + "Failed to send #{length(events)} events, attempt #{attempt} of #{@max_attempts}", + reason: inspect(failure(result)) + ) + + backoff = :rand.uniform(@retry_base_milliseconds * 2 ** (attempt - 1) + 1) - 1 + + case remaining(deadline) do + remaining when remaining <= backoff -> + {:kept, failure(result)} + + _ -> + Process.sleep(backoff) + deliver(config, events, deadline, attempt + 1) + end + end + + defp failure({:ok, status}), do: {:status, status} + defp failure({:error, reason}), do: reason + + # As an atom, :infinity compares greater than any number, e.g. in min/2. + defp remaining(:infinity), do: :infinity + defp remaining(deadline), do: max(deadline - System.monotonic_time(:millisecond), 0) + defp schedule_flush(%Configuration{events_flush_interval_milliseconds: interval}), do: Process.send_after(self(), :flush, interval) end diff --git a/lib/flagsmith_client_poller.ex b/lib/flagsmith_client_poller.ex index 8878cf3..aa62d8a 100644 --- a/lib/flagsmith_client_poller.ex +++ b/lib/flagsmith_client_poller.ex @@ -73,6 +73,17 @@ defmodule Flagsmith.Client.Poller do end end + # Stops the poller for the environment key, if one is running. + @spec stop(environment_key()) :: :ok | :noop + def stop(environment_key) do + with pid when is_pid(pid) <- whereis(environment_key), + :ok <- DynamicSupervisor.terminate_child(__MODULE__.Supervisor, pid) do + :ok + else + _ -> :noop + end + end + @spec start_link(Configuration.t()) :: {:ok, pid()} def start_link(%Configuration{environment_key: environment_key} = config) do name = via_tuple(environment_key) diff --git a/lib/flagsmith_engine.ex b/lib/flagsmith_engine.ex index 060394d..fea86ee 100644 --- a/lib/flagsmith_engine.ex +++ b/lib/flagsmith_engine.ex @@ -154,12 +154,23 @@ defmodule Flagsmith.Engine do defp to_feature_states(feature_states, flags) do Enum.map(feature_states, fn %{feature: %{name: name}} -> case Map.fetch!(flags, name) do - %FlagResult{enabled: enabled, value: value, metadata: %{feature_state: feature_state}} - when enabled === feature_state.enabled and value === feature_state.feature_state_value -> + %FlagResult{ + enabled: enabled, + value: value, + variant: variant, + metadata: %{feature_state: feature_state} + } + when enabled === feature_state.enabled and value === feature_state.feature_state_value and + variant === feature_state.variant -> feature_state - %FlagResult{enabled: enabled, value: value, metadata: %{feature_state: feature_state}} -> - %{feature_state | enabled: enabled, feature_state_value: value} + %FlagResult{ + enabled: enabled, + value: value, + variant: variant, + metadata: %{feature_state: feature_state} + } -> + %{feature_state | enabled: enabled, feature_state_value: value, variant: variant} end end) end diff --git a/lib/schemas/environment_feature_state.ex b/lib/schemas/environment_feature_state.ex index 4b9a92b..dfac852 100644 --- a/lib/schemas/environment_feature_state.ex +++ b/lib/schemas/environment_feature_state.ex @@ -2,7 +2,7 @@ defmodule Flagsmith.Schemas.Environment.FeatureState do use TypedEctoSchema import Ecto.Changeset - alias Flagsmith.Schemas.Environment + alias Flagsmith.Schemas.{Environment, Features} alias Flagsmith.Schemas.Types @moduledoc """ @@ -20,6 +20,10 @@ defmodule Flagsmith.Schemas.Environment.FeatureState do embeds_one(:feature, Environment.Feature) embeds_one(:feature_segment, __MODULE__.FeatureSegment) embeds_many(:multivariate_feature_state_values, Environment.MultivariateFeatureStateValue) + embeds_one(:metadata, Features.FeatureState.Metadata) + + # The variant an identity is served, set when evaluating its flags. + field(:variant, :string, virtual: true) end @doc false @@ -33,6 +37,7 @@ defmodule Flagsmith.Schemas.Environment.FeatureState do |> cast_embed(:feature) |> cast_embed(:feature_segment) |> cast_embed(:multivariate_feature_state_values) + |> cast_embed(:metadata) end @doc false diff --git a/lib/schemas/environment_multivariate_feature_option.ex b/lib/schemas/environment_multivariate_feature_option.ex index 8a00c52..936da88 100644 --- a/lib/schemas/environment_multivariate_feature_option.ex +++ b/lib/schemas/environment_multivariate_feature_option.ex @@ -9,6 +9,7 @@ defmodule Flagsmith.Schemas.Environment.MultivariateFeatureOption do @primary_key {:id, :id, autogenerate: false} typed_embedded_schema do field(:value, :string) + field(:key, :string) end @doc false @@ -16,7 +17,7 @@ defmodule Flagsmith.Schemas.Environment.MultivariateFeatureOption do @spec changeset(__MODULE__.t(), map()) :: Ecto.Changeset.t() def changeset(struct \\ %__MODULE__{}, params) do struct - |> cast(params, [:id, :value], empty_values: []) + |> cast(params, [:id, :value, :key], empty_values: []) end @doc false diff --git a/lib/schemas/flag.ex b/lib/schemas/flag.ex index 60cc3e1..aba4160 100644 --- a/lib/schemas/flag.ex +++ b/lib/schemas/flag.ex @@ -21,6 +21,8 @@ defmodule Flagsmith.Schemas.Flag do def from(%Environment.FeatureState{ enabled: enabled, feature_state_value: value, + variant: variant, + metadata: metadata, feature: %Environment.Feature{ name: name, id: id @@ -30,7 +32,9 @@ defmodule Flagsmith.Schemas.Flag do enabled: enabled, feature_name: name, value: value, - feature_id: id + feature_id: id, + variant: variant, + experiment: metadata && metadata.experiment } end diff --git a/lib/supervisors/events_processor_supervisor.ex b/lib/supervisors/events_processor_supervisor.ex index c0d83f1..d83b6aa 100644 --- a/lib/supervisors/events_processor_supervisor.ex +++ b/lib/supervisors/events_processor_supervisor.ex @@ -25,7 +25,7 @@ defmodule Flagsmith.Client.Events.Processor.Supervisor do id: Flagsmith.Client.Events.Processor, start: {Flagsmith.Client.Events.Processor, :start_link, [config]}, shutdown: 25_000, - restart: :permanent, + restart: :transient, type: :worker } ) diff --git a/sdk-spec/steps.exs b/sdk-spec/steps.exs index 6100244..fe44a15 100644 --- a/sdk-spec/steps.exs +++ b/sdk-spec/steps.exs @@ -46,6 +46,23 @@ defmodule SDKSpec.Steps do end end + # Create the SDK client with local evaluation and events enabled + def create_client_with_local_evaluation_and_events(environment_key, api_url, events_api_url) do + client = + Client.new( + environment_key: environment_key, + api_url: api_url, + enable_local_evaluation: true, + enable_events: true, + events_api_url: events_api_url + ) + + with :ok <- start_supervisor(), + {:ok, _environment} <- Client.get_environment(client) do + {:ok, client} + end + end + defp start_supervisor do case Flagsmith.Supervisor.start_link() do {:ok, _pid} -> :ok @@ -90,4 +107,23 @@ defmodule SDKSpec.Steps do metadata: metadata ) end + + # When the application tracks events "event_{first}" to "event_{last}" for identity "{identifier}" + def track_numbered_events(client, first, last, identifier) do + Enum.each(first..last, fn number -> + :ok = Client.track_event(client, "event_#{number}", identifier: identifier) + end) + end + + # When the application flushes events + def flush_events(client) do + Client.flush_events(client) + :ok + end + + # When the application closes the client with a timeout of {timeout} seconds + def close_client(client, timeout) do + Client.close(client, round(timeout * 1000)) + :ok + end end diff --git a/test/flagsmith_events_test.exs b/test/flagsmith_events_test.exs index 0dd6452..75ae4d3 100644 --- a/test/flagsmith_events_test.exs +++ b/test/flagsmith_events_test.exs @@ -2,7 +2,7 @@ defmodule Flagsmith.Client.Events.Test do use ExUnit.Case, async: false import ExUnit.CaptureLog - import Mox, only: [verify_on_exit!: 1, set_mox_global: 1, expect: 3, expect: 4] + import Mox, only: [verify_on_exit!: 1, set_mox_global: 1, expect: 3, expect: 4, stub: 3] alias Flagsmith.Client alias Flagsmith.Client.Events.Processor @@ -219,6 +219,148 @@ defmodule Flagsmith.Client.Events.Test do end end + describe "get_experiment_flag with local evaluation" do + setup do + Mox.stub_with(Flagsmith.Engine.MockHashing, Flagsmith.Engine.HashingUtils) + + [ + local_config: + Client.new( + environment_key: "events_test_key", + enable_local_evaluation: true, + enable_events: true, + events_api_url: @events_url + ) + ] + end + + for {case_name, rollout, allocation, variant, value} <- [ + {"to the variant it was served", 100.0, 100.0, "treatment", "new checkout"}, + {"to control when served no variant", 100.0, 0.0, "control", "control"} + ] do + test "an identity in a running experiment is exposed #{case_name}", %{ + local_config: config, + receive_events: receive_events + } do + # Given + expect(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + {:ok, + %Tesla.Env{ + status: 200, + body: experiment_environment(unquote(rollout), unquote(allocation)) + }} + end) + + expect(Tesla.Adapter.Mock, :call, receive_events) + + # When + flag = + Client.get_experiment_flag(config, "checkout", "user_123", [ + %{trait_key: "plan", trait_value: "premium"} + ]) + + :ok = Client.flush_events(config) + + # Then + assert %Schemas.Flag{ + value: unquote(value), + variant: unquote(variant), + experiment: %Schemas.Experiment{id: 9, in_experiment: true} + } = flag + + assert_receive {:events_request, _tesla_env, %{"events" => [event]}} + + assert %{ + "event" => "$flag_exposure", + "feature_name" => "checkout", + "identifier" => "user_123", + "value" => unquote(variant), + "traits" => %{"plan" => "premium"}, + "metadata" => %{"experiment_id" => 9} + } = event + end + end + + test "an identity a running experiment does not enroll is not exposed", %{ + local_config: config + } do + # Given + expect(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + {:ok, %Tesla.Env{status: 200, body: experiment_environment(0.0, 100.0)}} + end) + + # When + flag = Client.get_experiment_flag(config, "checkout", "user_123", []) + + # Then + assert %Schemas.Flag{ + value: "control", + experiment: %Schemas.Experiment{in_experiment: false} + } = flag + + assert :noop = Client.flush_events(config) + end + end + + # An environment document with an experiment on feature "checkout", as Flagsmith + # sends it: enrolled identities match the experiment's rollout segment, whose + # override serves the "treatment" variant to `allocation`% of them. + defp experiment_environment(rollout, allocation) do + feature_state = fn id, allocation, in_experiment -> + %{ + "feature" => %{"id" => 43, "name" => "checkout", "type" => "MULTIVARIATE"}, + "enabled" => true, + "django_id" => id, + "featurestate_uuid" => Ecto.UUID.generate(), + "feature_state_value" => "control", + "multivariate_feature_state_values" => [ + %{ + "multivariate_feature_option" => %{ + "id" => 9, + "key" => "treatment", + "value" => "new checkout" + }, + "percentage_allocation" => allocation, + "id" => id, + "mv_fs_value_uuid" => Ecto.UUID.generate() + } + ], + "metadata" => %{ + "experiment" => %{ + "id" => 9, + "name" => "checkout experiment", + "in_experiment" => in_experiment + } + } + } + end + + segment = %{ + "id" => 19, + "name" => "experiment-9-rollout", + "rules" => [ + %{ + "type" => "ALL", + "rules" => [], + "conditions" => [ + %{ + "operator" => "PERCENTAGE_SPLIT", + "value" => to_string(rollout), + "property_" => "$.identity.key" + } + ] + } + ], + "feature_states" => [ + Map.put(feature_state.(62, allocation, true), "feature_segment", %{"priority" => 0}) + ] + } + + Flagsmith.Engine.Test.Generators.map_env() + |> Map.put("feature_states", [feature_state.(61, 0.0, false)]) + |> put_in(["project", "segments"], [segment]) + end + describe "track_event" do test "a tracked event reaches Flagsmith with its value, traits and metadata", %{ config: config, @@ -396,32 +538,157 @@ defmodule Flagsmith.Client.Events.Test do assert_receive {:events_request, _, %{"events" => [%{"event" => "second"}]}}, 500 end - test "events Flagsmith fails to receive are sent again on the next flush", %{ - config: config, - receive_events: receive_events - } do + test "a batch is retried until the events API accepts it, giving up on each attempt after 3 seconds", + %{config: config, receive_events: receive_events} do # Given - expect(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + test_pid = self() + + expect(Tesla.Adapter.Mock, :call, fn tesla_env, _options -> + send(test_pid, {:attempt, tesla_env.opts[:adapter][:timeout]}) {:ok, %Tesla.Env{status: 503, body: "unavailable"}} end) + expect(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> {:error, :econnreset} end) expect(Tesla.Adapter.Mock, :call, receive_events) - :ok = Client.track_event(config, "checkout_completed", identifier: "user_123") + :ok = Client.track_event(config, "checkout", identifier: "user_123") # When + log = capture_log(fn -> assert :ok = Client.flush_events(config) end) + + # Then + assert_receive {:attempt, 3000} + assert_receive {:events_request, _tesla_env, %{"events" => [%{"event" => "checkout"}]}} + assert log =~ "attempt 1 of 3" + assert log =~ "attempt 2 of 3" + assert :noop = Client.flush_events(config) + end + + test "a batch that keeps failing is sent with the next flush, ahead of events tracked since", + %{config: config, receive_events: receive_events} do + # Given + expect(Tesla.Adapter.Mock, :call, 3, fn _tesla_env, _options -> + {:ok, %Tesla.Env{status: 503, body: "unavailable"}} + end) + + expect(Tesla.Adapter.Mock, :call, receive_events) + :ok = Client.track_event(config, "add_to_cart", identifier: "user_123") + log = capture_log(fn -> - assert {:error, "unavailable"} = Processor.flush(config.environment_key) + assert {:error, {:status, 503}} = Client.flush_events(config) end) - :ok = Client.track_event(config, "signed_out", identifier: "user_123") - :ok = Processor.flush(config.environment_key) + # When + :ok = Client.track_event(config, "checkout", identifier: "user_123") + :ok = Client.flush_events(config) + + # Then + assert log =~ "keeping them for the next flush" + assert_receive {:events_request, _tesla_env, %{"events" => events}} + assert ["add_to_cart", "checkout"] = Enum.map(events, & &1["event"]) + end + + for {case_name, failures} <- [ + {"a batch the events API rejects is dropped", [400]}, + {"a batch whose last attempt gets a server error is dropped", [503, 503, 500]} + ] do + test case_name, %{config: config, receive_events: receive_events} do + # Given + for status <- unquote(failures) do + expect(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + {:ok, %Tesla.Env{status: status, body: "failed"}} + end) + end + + expect(Tesla.Adapter.Mock, :call, receive_events) + :ok = Client.track_event(config, "add_to_cart", identifier: "user_123") + + log = + capture_log(fn -> + assert {:error, {:status, _}} = Client.flush_events(config) + end) + + # When + :ok = Client.track_event(config, "checkout", identifier: "user_123") + :ok = Client.flush_events(config) + + # Then + assert log =~ "dropping them" + assert_receive {:events_request, _tesla_env, %{"events" => [%{"event" => "checkout"}]}} + end + end + + test "a batch whose last attempt fails otherwise is kept, after server errors", %{ + config: config, + receive_events: receive_events + } do + # Given + for status <- [500, 500, 503] do + expect(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + {:ok, %Tesla.Env{status: status, body: "failed"}} + end) + end + + expect(Tesla.Adapter.Mock, :call, receive_events) + :ok = Client.track_event(config, "add_to_cart", identifier: "user_123") + capture_log(fn -> assert {:error, {:status, 503}} = Client.flush_events(config) end) + + # When + :ok = Client.track_event(config, "checkout", identifier: "user_123") + :ok = Client.flush_events(config) # Then - assert log =~ "Failed to send events to Flagsmith, keeping them to retry" + assert_receive {:events_request, _tesla_env, %{"events" => events}} + assert ["add_to_cart", "checkout"] = Enum.map(events, & &1["event"]) + end + + for status <- [401, 403] do + test "an events API refusing the environment key with #{status} stops event tracking", %{ + config: config + } do + # Given + expect(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + {:ok, %Tesla.Env{status: unquote(status), body: "refused"}} + end) + + :ok = Client.track_event(config, "add_to_cart", identifier: "user_123") + + log = + capture_log(fn -> + assert {:error, {:status, unquote(status)}} = Client.flush_events(config) + end) + + # When + :ok = Client.track_event(config, "checkout", identifier: "user_123") + + # Then + assert log =~ "stopping event tracking" + assert :noop = Client.flush_events(config) + end + end + + test "a full buffer drops its oldest event", %{config: config, receive_events: receive_events} do + # Given + expect(Tesla.Adapter.Mock, :call, 3, fn _tesla_env, _options -> + {:ok, %Tesla.Env{status: 503, body: "unavailable"}} + end) + + expect(Tesla.Adapter.Mock, :call, receive_events) + log = + capture_log(fn -> + for n <- 1..1000, do: :ok = Client.track_event(config, "event_#{n}") + assert :noop = Client.flush_events(config) + + # When + :ok = Client.track_event(config, "event_1001") + :ok = Client.flush_events(config) + end) + + # Then + assert log =~ "dropping the oldest event_1 event" assert_receive {:events_request, _tesla_env, %{"events" => events}} - assert ["checkout_completed", "signed_out"] = Enum.map(events, & &1["event"]) + assert Enum.map(events, & &1["event"]) == for(n <- 2..1001, do: "event_#{n}") end test "a full buffer of events is sent without waiting for the flush interval", %{ @@ -456,6 +723,56 @@ defmodule Flagsmith.Client.Events.Test do assert %{"event" => "checkout_completed"} = event end + test "closing the client sends the buffered events, and stops sending events", %{ + config: config, + receive_events: receive_events + } do + # Given + expect(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + {:ok, %Tesla.Env{status: 503, body: "unavailable"}} + end) + + expect(Tesla.Adapter.Mock, :call, receive_events) + :ok = Client.track_event(config, "checkout", identifier: "user_123") + + # When + capture_log(fn -> assert :ok = Client.close(config) end) + + # Then + assert_receive {:events_request, _tesla_env, %{"events" => [%{"event" => "checkout"}]}} + assert :undefined = Processor.whereis(config.environment_key) + end + + test "closing the client returns within its timeout when the events API does not answer", %{ + config: config + } do + # Given + test_pid = self() + + stub(Tesla.Adapter.Mock, :call, fn tesla_env, _options -> + timeout = tesla_env.opts[:adapter][:timeout] + send(test_pid, {:attempt, timeout}) + Process.sleep(timeout) + {:error, :timeout} + end) + + :ok = Client.track_event(config, "checkout", identifier: "user_123") + + # When + {elapsed, result} = + :timer.tc(fn -> capture_log(fn -> send(test_pid, Client.close(config, 200)) end) end) + + # Then + assert_received {:error, :timeout} + assert_receive {:attempt, timeout} when timeout <= 200 + assert elapsed < 400_000 + assert is_binary(result) + end + + test "flushing events requires events to be enabled" do + assert {:error, :events_disabled} = Client.flush_events(environment_key: "A") + end + test "nothing is sent when there are no events", %{config: config} do # Given expect(Tesla.Adapter.Mock, :call, fn _, _ -> {:ok, %Tesla.Env{status: 202}} end) From f81d3f2bd037798b3b1d04dc65f9d44830867b67 Mon Sep 17 00:00:00 2001 From: "flagsmithsmith[bot]" <346993984+flagsmithsmith[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:36:23 +0000 Subject: [PATCH 4/6] fix(Events): Kill the events processor when closing the client times out `close/2` stopped waiting when its timeout expired, but a flush already running kept retrying for up to ~12 seconds. The processor is now killed on timeout, and is started as a temporary child so that its supervisor doesn't restart it; tracking an event starts a new one, as before. Co-Authored-By: Claude Opus 5.5 --- lib/flagsmith_client_events_processor.ex | 17 ++++++++++-- .../events_processor_supervisor.ex | 4 ++- test/flagsmith_events_test.exs | 27 +++++++++++++++++++ 3 files changed, 45 insertions(+), 3 deletions(-) diff --git a/lib/flagsmith_client_events_processor.ex b/lib/flagsmith_client_events_processor.ex index cf26049..650d780 100644 --- a/lib/flagsmith_client_events_processor.ex +++ b/lib/flagsmith_client_events_processor.ex @@ -87,7 +87,8 @@ defmodule Flagsmith.Client.Events.Processor do @doc """ Sends the buffered events, and stops the processor, waiting for at most `timeout` - milliseconds. Events not sent by then are dropped. + milliseconds. Events not sent by then are dropped: a processor still sending when + the timeout expires, e.g. retrying a flush already running, is killed. """ @spec close(environment_key(), non_neg_integer()) :: :ok | :noop | {:error, term()} def close(environment_key, timeout \\ @default_close_timeout_milliseconds) do @@ -98,9 +99,10 @@ defmodule Flagsmith.Client.Events.Processor do try do GenServer.call(pid, {:close, deadline}, timeout) catch - # The processor is still sending a batch: it stops once done, past the deadline. + # The processor is still sending a batch, which may take several more attempts. :exit, {:timeout, _} -> Logger.warning("Gave up sending events after #{timeout} milliseconds while closing") + kill(pid) {:error, :timeout} :exit, {reason, _} when reason in [:noproc, :normal, :shutdown] -> @@ -112,6 +114,17 @@ defmodule Flagsmith.Client.Events.Processor do end end + # Kills the processor, returning once it's gone. It traps exits, so only :kill stops + # it while it's busy sending; its supervisor doesn't restart it, being :temporary. + defp kill(pid) do + ref = Process.monitor(pid) + Process.exit(pid, :kill) + + receive do + {:DOWN, ^ref, :process, ^pid, _reason} -> :ok + end + end + @doc false @spec processor_id(environment_key()) :: processor_identifier() def processor_id(environment_key), do: {__MODULE__, environment_key} diff --git a/lib/supervisors/events_processor_supervisor.ex b/lib/supervisors/events_processor_supervisor.ex index d83b6aa..52dcd63 100644 --- a/lib/supervisors/events_processor_supervisor.ex +++ b/lib/supervisors/events_processor_supervisor.ex @@ -25,7 +25,9 @@ defmodule Flagsmith.Client.Events.Processor.Supervisor do id: Flagsmith.Client.Events.Processor, start: {Flagsmith.Client.Events.Processor, :start_link, [config]}, shutdown: 25_000, - restart: :transient, + # Not restarted once stopped, by closing the client or killing it when closing + # times out: `Flagsmith.Client.Events.Processor.track/2` starts a new one if needed. + restart: :temporary, type: :worker } ) diff --git a/test/flagsmith_events_test.exs b/test/flagsmith_events_test.exs index 75ae4d3..4c42dc0 100644 --- a/test/flagsmith_events_test.exs +++ b/test/flagsmith_events_test.exs @@ -769,6 +769,33 @@ defmodule Flagsmith.Client.Events.Test do assert is_binary(result) end + test "closing the client stops a flush still sending when its timeout expires", %{ + config: config + } do + # Given a flush already sending, which the events API keeps failing slowly + test_pid = self() + + stub(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + send(test_pid, :attempt) + Process.sleep(100) + {:ok, %Tesla.Env{status: 503, body: "unavailable"}} + end) + + :ok = Client.track_event(config, "checkout", identifier: "user_123") + pid = Processor.whereis(config.environment_key) + spawn(fn -> catch_exit(Processor.flush(config.environment_key)) end) + assert_receive :attempt + + # When + log = capture_log(fn -> assert {:error, :timeout} = Client.close(config, 50) end) + + # Then + assert log =~ "Gave up sending events after 50 milliseconds while closing" + refute Process.alive?(pid) + assert :undefined = Processor.whereis(config.environment_key) + refute_receive :attempt, 500 + end + test "flushing events requires events to be enabled" do assert {:error, :events_disabled} = Client.flush_events(environment_key: "A") end From 19b4272cfb9223ce7629ffe973a0b2bf137f1cb5 Mon Sep 17 00:00:00 2001 From: "flagsmithsmith[bot]" <346993984+flagsmithsmith[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:10:51 +0000 Subject: [PATCH 5/6] fix(Events): Send batches in a task, so that tracking and closing don't wait on them The events processor sent batches, retries included, inside the GenServer, for up to ~12 seconds. Events tracked meanwhile piled up in its mailbox, past the buffer's 1000-event limit, and a flush caller exited when closing the client killed the processor. Batches are now sent by a task. The processor keeps buffering events while one is in flight, dropping the oldest once full; flush callers wait for the batch in flight; and closing abandons it at the deadline, replying `{:error, :closed}` to flush callers instead of killing the processor. `flush/1` no longer exits if the processor stops between being looked up and called. Co-Authored-By: Claude Opus 5.5 --- lib/flagsmith_client_events_processor.ex | 214 +++++++++++++++++++---- test/flagsmith_events_test.exs | 84 ++++++++- 2 files changed, 259 insertions(+), 39 deletions(-) diff --git a/lib/flagsmith_client_events_processor.ex b/lib/flagsmith_client_events_processor.ex index 650d780..f5465b0 100644 --- a/lib/flagsmith_client_events_processor.ex +++ b/lib/flagsmith_client_events_processor.ex @@ -23,6 +23,7 @@ defmodule Flagsmith.Client.Events.Processor do @request_timeout_milliseconds 3000 @retry_base_milliseconds if(Mix.env() == :test, do: 20, else: 1000) @default_close_timeout_milliseconds 5000 + @close_margin_milliseconds 500 # Statuses that a later attempt may not get, besides server errors. @retried_statuses [408, 429] # Statuses meaning the events API refuses the environment key. @@ -36,7 +37,14 @@ defmodule Flagsmith.Client.Events.Processor do # Whether events were tracked since the last attempt to send the buffer. unsent: false, refused: false, - exposure_keys: MapSet.new() + exposure_keys: MapSet.new(), + # The batch being sent, by a task, so that the processor keeps buffering events + # (and applying the buffer's limit) while it waits on the events API. + sending: nil, + # Callers of flush/1 waiting for the batch being sent. + flush_waiters: [], + # The caller of close/2, once closing. + closing: nil ] ################################# @@ -76,30 +84,40 @@ defmodule Flagsmith.Client.Events.Processor do returns once each of them has been delivered, dropped, or kept for the next flush. Returns `:noop` when there is nothing to send, including when the buffer only holds events already kept from a failed flush, which the next timed flush sends. + Never exits: returns `{:error, :closed}` if the processor is closed meanwhile. """ @spec flush(environment_key()) :: :ok | :noop | {:error, term()} def flush(environment_key) do case whereis(environment_key) do - pid when is_pid(pid) -> GenServer.call(pid, :flush, :infinity) - :undefined -> :noop + pid when is_pid(pid) -> + try do + GenServer.call(pid, :flush, :infinity) + catch + # The processor stopped between being looked up and called. + :exit, {reason, _} when reason in [:noproc, :normal, :shutdown] -> :noop + :exit, {reason, _} -> {:error, reason} + end + + :undefined -> + :noop end end @doc """ - Sends the buffered events, and stops the processor, waiting for at most `timeout` - milliseconds. Events not sent by then are dropped: a processor still sending when - the timeout expires, e.g. retrying a flush already running, is killed. + Sends the buffered events, and stops the processor, returning after at most + `timeout` milliseconds. Events not sent by then are dropped, and a batch still being + sent, e.g. retried by a flush already running, is abandoned: no attempt to send it + is made after this returns. """ @spec close(environment_key(), non_neg_integer()) :: :ok | :noop | {:error, term()} def close(environment_key, timeout \\ @default_close_timeout_milliseconds) do case whereis(environment_key) do pid when is_pid(pid) -> - deadline = System.monotonic_time(:millisecond) + timeout - try do - GenServer.call(pid, {:close, deadline}, timeout) + # The processor replies by the deadline itself; the margin only covers one + # that can't, for which it's killed. + GenServer.call(pid, {:close, timeout}, timeout + @close_margin_milliseconds) catch - # The processor is still sending a batch, which may take several more attempts. :exit, {:timeout, _} -> Logger.warning("Gave up sending events after #{timeout} milliseconds while closing") kill(pid) @@ -115,7 +133,7 @@ defmodule Flagsmith.Client.Events.Processor do end # Kills the processor, returning once it's gone. It traps exits, so only :kill stops - # it while it's busy sending; its supervisor doesn't restart it, being :temporary. + # it; its supervisor doesn't restart it, being :temporary. defp kill(pid) do ref = Process.monitor(pid) Process.exit(pid, :kill) @@ -197,31 +215,71 @@ defmodule Flagsmith.Client.Events.Processor do end @impl GenServer + def handle_call(:flush, from, %__MODULE__{sending: %{}} = data), + do: {:noreply, add_flush_waiter(data, from)} + def handle_call(:flush, _from, %__MODULE__{unsent: false} = data), do: {:reply, :noop, data} - def handle_call(:flush, _from, %__MODULE__{} = data) do - {result, data} = do_flush(data, :infinity) - {:reply, result, data} - end + def handle_call(:flush, from, %__MODULE__{} = data), + do: {:noreply, data |> send_batch(:infinity) |> add_flush_waiter(from)} + + # Already closing: the first caller is the one waiting for the buffered events. + def handle_call({:close, _timeout}, _from, %__MODULE__{closing: %{}} = data), + do: {:reply, :noop, data} - def handle_call({:close, deadline}, _from, %__MODULE__{} = data) do - {result, _data} = do_flush(data, deadline) - {:stop, :normal, result, %{data | buffer: :queue.new(), buffered: 0}} + def handle_call({:close, timeout}, from, %__MODULE__{} = data) do + Process.send_after(self(), :close_timeout, timeout) + deadline = System.monotonic_time(:millisecond) + timeout + closing = %{from: from, timeout: timeout, deadline: deadline, final_batch: false} + + case data.sending do + # Waits for the batch being sent, until the deadline, then sends what's left. + %{} -> {:noreply, %{data | closing: closing}} + nil -> close_next(%{data | closing: closing}, :noop) + end end @impl GenServer def handle_info(:flush, %__MODULE__{configuration: config} = data) do - {_, data} = do_flush(data, :infinity) schedule_flush(config) - {:noreply, data} + + case data do + %{sending: nil, closing: nil} -> {:noreply, send_batch(data, :infinity)} + _ -> {:noreply, data} + end + end + + def handle_info({ref, outcome}, %__MODULE__{sending: %{task: %Task{ref: ref}}} = data) do + Process.demonitor(ref, [:flush]) + sent(data, outcome) + end + + def handle_info( + {:DOWN, ref, :process, _pid, reason}, + %__MODULE__{sending: %{task: %Task{ref: ref}}} = data + ), + do: sent(data, {:kept, reason}) + + def handle_info(:close_timeout, %__MODULE__{closing: %{timeout: timeout}} = data) do + Logger.warning("Gave up sending events after #{timeout} milliseconds while closing") + stop_closing(abandon_batch(data), {:error, :timeout}) end def handle_info(_, data), do: {:noreply, data} @impl GenServer def terminate(_reason, %__MODULE__{} = data) do - do_flush(data, System.monotonic_time(:millisecond) + @default_close_timeout_milliseconds) + data = abandon_batch(data) + + case take_batch(data) do + nil -> + :noop + + {events, data} -> + deadline = System.monotonic_time(:millisecond) + @default_close_timeout_milliseconds + apply_outcome(data, events, deliver(data.configuration, events, deadline, 1)) + end end defp exposure_key(%{event: @flag_exposure_event} = event), @@ -230,7 +288,7 @@ defmodule Flagsmith.Client.Events.Processor do defp exposure_key(_), do: nil # A full buffer drops its oldest event for the new one. Filling it up sends it - # without waiting for the flush interval. + # without waiting for the flush interval, or as soon as the batch being sent is done. defp buffer(%__MODULE__{buffered: @max_buffered_events} = data, event) do {{:value, dropped}, buffer} = :queue.out(data.buffer) Logger.warning("Event buffer is full, dropping the oldest #{dropped.event} event") @@ -245,28 +303,102 @@ defmodule Flagsmith.Client.Events.Processor do unsent: true } - case data.buffered do - @max_buffered_events -> elem(do_flush(data, :infinity), 1) + case {data.buffered, data.sending, data.closing} do + {@max_buffered_events, nil, nil} -> send_batch(data, :infinity) _ -> data end end - defp do_flush(%__MODULE__{buffered: 0} = data, _deadline), do: {:noop, data} + defp add_flush_waiter(data, from), do: %{data | flush_waiters: [from | data.flush_waiters]} + + # Starts sending the buffered events, in a task, unless there are none. + defp send_batch(%__MODULE__{configuration: config} = data, deadline) do + case take_batch(data) do + nil -> + data + + {events, data} -> + task = Task.async(fn -> deliver(config, events, deadline, 1) end) + %{data | sending: %{task: task, events: events}} + end + end + + defp take_batch(%__MODULE__{buffered: 0}), do: nil + + defp take_batch(%__MODULE__{} = data), + do: {:queue.to_list(data.buffer), %{data | buffer: :queue.new(), buffered: 0, unsent: false}} + + # Kills the task sending a batch, if any, putting the batch back in the buffer. + defp abandon_batch(%__MODULE__{sending: nil} = data), do: data + + defp abandon_batch(%__MODULE__{sending: %{task: task, events: events}} = data) do + Task.shutdown(task, :brutal_kill) + keep(%{data | sending: nil}, events) + end - defp do_flush(%__MODULE__{configuration: config} = data, deadline) do - events = :queue.to_list(data.buffer) - sent = %{data | buffer: :queue.new(), buffered: 0, unsent: false, exposure_keys: MapSet.new()} + # The batch being sent is done with: replies to whoever waits for it, or sends what + # was tracked meanwhile to the callers of flush/1 waiting for it. + defp sent(%__MODULE__{sending: %{events: events}} = data, outcome) do + {result, data} = apply_outcome(%{data | sending: nil}, events, outcome) + + cond do + data.closing != nil -> + close_next(data, result) + + data.flush_waiters != [] and data.unsent -> + {:noreply, send_batch(data, :infinity)} + + true -> + Enum.each(data.flush_waiters, &GenServer.reply(&1, result)) + data = %{data | flush_waiters: []} + + # Events tracked meanwhile filled the buffer up; a kept batch alone doesn't. + case {data.buffered, data.unsent} do + {@max_buffered_events, true} -> {:noreply, send_batch(data, :infinity)} + _ -> {:noreply, data} + end + end + end - case deliver(config, events, deadline, 1) do + # Sends the buffer once while closing, by the deadline, then stops. + defp close_next(%__MODULE__{closing: %{final_batch: false} = closing} = data, result) do + case send_batch(data, closing.deadline) do + %{sending: nil} = data -> stop_closing(data, result) + data -> {:noreply, %{data | closing: %{closing | final_batch: true}}} + end + end + + defp close_next(%__MODULE__{} = data, result), do: stop_closing(data, result) + + defp stop_closing(%__MODULE__{closing: closing} = data, result) do + GenServer.reply(closing.from, result) + Enum.each(data.flush_waiters, &GenServer.reply(&1, {:error, :closed})) + + {:stop, :normal, %{data | buffer: :queue.new(), buffered: 0, flush_waiters: [], closing: nil}} + end + + # What became of a batch: forgets it once delivered or dropped, and puts it back in + # the buffer, ahead of the events tracked since, when kept for the next flush. + defp apply_outcome(data, events, outcome) do + case outcome do :delivered -> - {:ok, sent} + {:ok, forget_exposures(data, events)} {:dropped, reason} -> - {{:error, reason}, sent} + {{:error, reason}, forget_exposures(data, events)} {:refused, reason} -> Logger.error("The events API refused the environment key, stopping event tracking") - {{:error, reason}, %{sent | refused: true}} + + {{:error, reason}, + %{ + data + | buffer: :queue.new(), + buffered: 0, + unsent: false, + refused: true, + exposure_keys: MapSet.new() + }} {:kept, reason} -> Logger.warning("Failed to send events to Flagsmith, keeping them for the next flush", @@ -274,10 +406,26 @@ defmodule Flagsmith.Client.Events.Processor do events: length(events) ) - {{:error, reason}, %{data | unsent: false}} + {{:error, reason}, keep(data, events)} end end + defp keep(data, events) do + kept = events ++ :queue.to_list(data.buffer) + dropped = length(kept) - @max_buffered_events + kept = if dropped > 0, do: Enum.drop(kept, dropped), else: kept + + if dropped > 0, + do: Logger.warning("Event buffer is full, dropping the oldest #{dropped} events") + + %{data | buffer: :queue.from_list(kept), buffered: length(kept)} + end + + defp forget_exposures(data, events) do + keys = events |> Enum.map(&exposure_key/1) |> Enum.reject(&is_nil/1) |> MapSet.new() + %{data | exposure_keys: MapSet.difference(data.exposure_keys, keys)} + end + # Sends a batch up to @max_attempts times, backing off with full jitter between # attempts, until `deadline`. Returns what became of the batch: delivered, dropped # (rejected by the events API, or failed with a 500 on its last attempt), refused diff --git a/test/flagsmith_events_test.exs b/test/flagsmith_events_test.exs index 4c42dc0..3e638fd 100644 --- a/test/flagsmith_events_test.exs +++ b/test/flagsmith_events_test.exs @@ -678,7 +678,8 @@ defmodule Flagsmith.Client.Events.Test do log = capture_log(fn -> for n <- 1..1000, do: :ok = Client.track_event(config, "event_#{n}") - assert :noop = Client.flush_events(config) + # Waits for, or finds done, the batch the full buffer sent by itself. + assert Client.flush_events(config) in [:noop, {:error, {:status, 503}}] # When :ok = Client.track_event(config, "event_1001") @@ -704,7 +705,45 @@ defmodule Flagsmith.Client.Events.Test do # Then assert_receive {:events_request, _tesla_env, %{"events" => events}}, 1000 assert length(events) == 1000 - assert :noop = Processor.flush(config.environment_key) + assert Processor.flush(config.environment_key) in [:ok, :noop] + end + + test "events tracked while a batch is being sent are buffered, up to the buffer's limit", %{ + config: config + } do + # Given a full buffer, whose batch the events API holds on to + test_pid = self() + + stub(Tesla.Adapter.Mock, :call, fn tesla_env, _options -> + send(test_pid, {:holding, self(), Jason.decode!(tesla_env.body)}) + + receive do + :release -> {:ok, %Tesla.Env{status: 202, body: ""}} + end + end) + + for n <- 1..1000, do: :ok = Client.track_event(config, "event_#{n}") + assert_receive {:holding, request, %{"events" => first_batch}}, 1000 + + # When + log = + capture_log(fn -> + for n <- 1001..2500, do: :ok = Client.track_event(config, "event_#{n}") + + # Then the processor keeps up, holding at most a full buffer besides the batch + pid = Processor.whereis(config.environment_key) + assert %Processor{buffered: 1000, sending: %{}} = :sys.get_state(pid) + assert {:message_queue_len, 0} = Process.info(pid, :message_queue_len) + end) + + assert log =~ "dropping the oldest event_1001 event" + assert Enum.map(first_batch, & &1["event"]) == for(n <- 1..1000, do: "event_#{n}") + + # And the full buffer is sent once the batch is done with + send(request, :release) + assert_receive {:holding, request, %{"events" => second_batch}}, 1000 + send(request, :release) + assert Enum.map(second_batch, & &1["event"]) == for(n <- 1501..2500, do: "event_#{n}") end test "buffered events are sent when the application stops", %{ @@ -783,19 +822,52 @@ defmodule Flagsmith.Client.Events.Test do :ok = Client.track_event(config, "checkout", identifier: "user_123") pid = Processor.whereis(config.environment_key) - spawn(fn -> catch_exit(Processor.flush(config.environment_key)) end) + monitor = Process.monitor(pid) + spawn(fn -> send(test_pid, {:flushed, Processor.flush(config.environment_key)}) end) assert_receive :attempt # When log = capture_log(fn -> assert {:error, :timeout} = Client.close(config, 50) end) - # Then + # Then the flush caller is told, rather than exiting, and nothing more is sent assert log =~ "Gave up sending events after 50 milliseconds while closing" - refute Process.alive?(pid) - assert :undefined = Processor.whereis(config.environment_key) + assert_receive {:flushed, {:error, :closed}} + assert_receive {:DOWN, ^monitor, :process, ^pid, :normal} refute_receive :attempt, 500 end + test "closing the client while it's already closing is a no-op", %{config: config} do + # Given a close waiting on the events API + test_pid = self() + + stub(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + send(test_pid, {:holding, self()}) + + receive do + :release -> {:ok, %Tesla.Env{status: 202, body: ""}} + end + end) + + :ok = Client.track_event(config, "checkout", identifier: "user_123") + spawn(fn -> send(test_pid, {:closed, Client.close(config)}) end) + assert_receive {:holding, request} + + # When / Then + assert :noop = Client.close(config) + send(request, :release) + assert_receive {:closed, :ok} + end + + test "flushing events after the processor has stopped is a no-op", %{config: config} do + # Given + expect(Tesla.Adapter.Mock, :call, fn _, _ -> {:ok, %Tesla.Env{status: 202}} end) + :ok = Client.track_event(config, "checkout", identifier: "user_123") + :ok = Client.close(config) + + # When / Then + assert :noop = Client.flush_events(config) + end + test "flushing events requires events to be enabled" do assert {:error, :events_disabled} = Client.flush_events(environment_key: "A") end From 11df3af3677495eb38c4770116b918b116dc46a4 Mon Sep 17 00:00:00 2001 From: "flagsmithsmith[bot]" <346993984+flagsmithsmith[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:53:26 +0000 Subject: [PATCH 6/6] fix(Events): Bound how long a flush waits, and track dropped exposures again - A flush arriving while a batch is being sent, with events tracked since, now waits for one more batch at most, then gets a reply. Previously it waited until a batch ended with nothing tracked meanwhile, which steady tracking could postpone indefinitely. A flush arriving with nothing tracked since only waits for the batch in flight. - Exposures dropped by a full buffer, or when a kept batch no longer fits it, are forgotten, so that they're tracked again. Previously their keys stayed, and those exposures were skipped as duplicates for the life of the processor. Co-Authored-By: Claude Opus 5.5 --- lib/flagsmith_client_events_processor.ex | 51 ++++++---- test/flagsmith_events_test.exs | 115 +++++++++++++++++++++++ 2 files changed, 150 insertions(+), 16 deletions(-) diff --git a/lib/flagsmith_client_events_processor.ex b/lib/flagsmith_client_events_processor.ex index f5465b0..db08bed 100644 --- a/lib/flagsmith_client_events_processor.ex +++ b/lib/flagsmith_client_events_processor.ex @@ -43,6 +43,9 @@ defmodule Flagsmith.Client.Events.Processor do sending: nil, # Callers of flush/1 waiting for the batch being sent. flush_waiters: [], + # Callers of flush/1 who arrived while a batch was being sent, with events tracked + # since: they wait for one more batch, then get a reply whatever is tracked meanwhile. + next_flush_waiters: [], # The caller of close/2, once closing. closing: nil ] @@ -215,6 +218,9 @@ defmodule Flagsmith.Client.Events.Processor do end @impl GenServer + def handle_call(:flush, from, %__MODULE__{sending: %{}, unsent: true} = data), + do: {:noreply, %{data | next_flush_waiters: [from | data.next_flush_waiters]}} + def handle_call(:flush, from, %__MODULE__{sending: %{}} = data), do: {:noreply, add_flush_waiter(data, from)} @@ -292,7 +298,7 @@ defmodule Flagsmith.Client.Events.Processor do defp buffer(%__MODULE__{buffered: @max_buffered_events} = data, event) do {{:value, dropped}, buffer} = :queue.out(data.buffer) Logger.warning("Event buffer is full, dropping the oldest #{dropped.event} event") - %{data | buffer: :queue.in(event, buffer), unsent: true} + forget_exposures(%{data | buffer: :queue.in(event, buffer), unsent: true}, [dropped]) end defp buffer(%__MODULE__{} = data, event) do @@ -336,21 +342,24 @@ defmodule Flagsmith.Client.Events.Processor do keep(%{data | sending: nil}, events) end - # The batch being sent is done with: replies to whoever waits for it, or sends what - # was tracked meanwhile to the callers of flush/1 waiting for it. + # The batch being sent is done with: replies to the callers of flush/1 waiting for it, + # and sends one more batch for those who arrived meanwhile, with events tracked since. defp sent(%__MODULE__{sending: %{events: events}} = data, outcome) do {result, data} = apply_outcome(%{data | sending: nil}, events, outcome) + reply_all(data.flush_waiters, result) + data = %{data | flush_waiters: []} cond do data.closing != nil -> close_next(data, result) - data.flush_waiters != [] and data.unsent -> - {:noreply, send_batch(data, :infinity)} + data.next_flush_waiters != [] and data.unsent -> + data = send_batch(data, :infinity) + {:noreply, %{data | flush_waiters: data.next_flush_waiters, next_flush_waiters: []}} true -> - Enum.each(data.flush_waiters, &GenServer.reply(&1, result)) - data = %{data | flush_waiters: []} + reply_all(data.next_flush_waiters, result) + data = %{data | next_flush_waiters: []} # Events tracked meanwhile filled the buffer up; a kept batch alone doesn't. case {data.buffered, data.unsent} do @@ -360,6 +369,8 @@ defmodule Flagsmith.Client.Events.Processor do end end + defp reply_all(callers, reply), do: Enum.each(callers, &GenServer.reply(&1, reply)) + # Sends the buffer once while closing, by the deadline, then stops. defp close_next(%__MODULE__{closing: %{final_batch: false} = closing} = data, result) do case send_batch(data, closing.deadline) do @@ -372,9 +383,17 @@ defmodule Flagsmith.Client.Events.Processor do defp stop_closing(%__MODULE__{closing: closing} = data, result) do GenServer.reply(closing.from, result) - Enum.each(data.flush_waiters, &GenServer.reply(&1, {:error, :closed})) - - {:stop, :normal, %{data | buffer: :queue.new(), buffered: 0, flush_waiters: [], closing: nil}} + reply_all(data.flush_waiters ++ data.next_flush_waiters, {:error, :closed}) + + {:stop, :normal, + %{ + data + | buffer: :queue.new(), + buffered: 0, + flush_waiters: [], + next_flush_waiters: [], + closing: nil + }} end # What became of a batch: forgets it once delivered or dropped, and puts it back in @@ -411,16 +430,16 @@ defmodule Flagsmith.Client.Events.Processor do end defp keep(data, events) do - kept = events ++ :queue.to_list(data.buffer) - dropped = length(kept) - @max_buffered_events - kept = if dropped > 0, do: Enum.drop(kept, dropped), else: kept + {dropped, kept} = + Enum.split(events ++ :queue.to_list(data.buffer), -@max_buffered_events) - if dropped > 0, - do: Logger.warning("Event buffer is full, dropping the oldest #{dropped} events") + if dropped != [], + do: Logger.warning("Event buffer is full, dropping the oldest #{length(dropped)} events") - %{data | buffer: :queue.from_list(kept), buffered: length(kept)} + forget_exposures(%{data | buffer: :queue.from_list(kept), buffered: length(kept)}, dropped) end + # Forgets the exposures among events no longer buffered, so that they're tracked again. defp forget_exposures(data, events) do keys = events |> Enum.map(&exposure_key/1) |> Enum.reject(&is_nil/1) |> MapSet.new() %{data | exposure_keys: MapSet.difference(data.exposure_keys, keys)} diff --git a/test/flagsmith_events_test.exs b/test/flagsmith_events_test.exs index 3e638fd..ded052c 100644 --- a/test/flagsmith_events_test.exs +++ b/test/flagsmith_events_test.exs @@ -2,6 +2,7 @@ defmodule Flagsmith.Client.Events.Test do use ExUnit.Case, async: false import ExUnit.CaptureLog + import Flagsmith.Test.Helpers, only: [wait_until: 2] import Mox, only: [verify_on_exit!: 1, set_mox_global: 1, expect: 3, expect: 4, stub: 3] alias Flagsmith.Client @@ -808,6 +809,120 @@ defmodule Flagsmith.Client.Events.Test do assert is_binary(result) end + test "a flush waits for one more batch at most while events keep being tracked", %{ + config: config + } do + # Given an events API holding on to each batch until released + test_pid = self() + + stub(Tesla.Adapter.Mock, :call, fn tesla_env, _options -> + events = Enum.map(Jason.decode!(tesla_env.body)["events"], & &1["event"]) + send(test_pid, {:holding, self(), events}) + + receive do + :release -> {:ok, %Tesla.Env{status: 202, body: ""}} + end + end) + + flush = fn n -> + spawn(fn -> send(test_pid, {:flushed, n, Client.flush_events(config)}) end) + end + + :ok = Client.track_event(config, "first") + pid = Processor.whereis(config.environment_key) + flush.(1) + assert_receive {:holding, request, ["first"]} + + # When a flush arrives while that batch is sent, with an event tracked since + :ok = Client.track_event(config, "second") + flush.(2) + assert wait_until(fn -> :sys.get_state(pid).next_flush_waiters != [] end, 500) + send(request, :release) + + # Then it waits for the batch in flight and one more, whatever is tracked meanwhile + assert_receive {:flushed, 1, :ok} + assert_receive {:holding, request, ["second"]} + :ok = Client.track_event(config, "third") + _ = :sys.get_state(pid) + send(request, :release) + assert_receive {:flushed, 2, :ok} + refute_receive {:holding, _, _}, 100 + end + + test "an exposure dropped from a full buffer is tracked again", %{config: config} do + # Given an exposure dropped from a buffer the events API failed to receive + stub(Tesla.Adapter.Mock, :call, fn _tesla_env, _options -> + {:ok, %Tesla.Env{status: 503, body: "unavailable"}} + end) + + exposure = [identifier: "user_123", value: "treatment"] + + capture_log(fn -> + :ok = Client.track_exposure_event(config, "banner", exposure) + for n <- 2..1000, do: :ok = Client.track_event(config, "event_#{n}") + assert Client.flush_events(config) in [:noop, {:error, {:status, 503}}] + :ok = Client.track_event(config, "event_1001") + end) + + # When + pid = Processor.whereis(config.environment_key) + + {state, log} = + with_log(fn -> + :ok = Client.track_exposure_event(config, "banner", exposure) + :sys.get_state(pid) + end) + + # Then it's buffered again, the buffer dropping its oldest event for it + assert log =~ "dropping the oldest event_2 event" + events = :queue.to_list(state.buffer) + assert ["event_3" | _] = Enum.map(events, & &1.event) + assert %{event: "$flag_exposure", feature_name: "banner"} = List.last(events) + end + + test "an exposure dropped when a kept batch no longer fits the buffer is tracked again", %{ + config: config + } do + # Given a batch with an exposure, held then failed by the events API, while the + # buffer fills up with events tracked meanwhile + test_pid = self() + + stub(Tesla.Adapter.Mock, :call, fn tesla_env, _options -> + events = Enum.map(Jason.decode!(tesla_env.body)["events"], & &1["event"]) + send(test_pid, {:holding, self(), events}) + + receive do + :release -> {:ok, %Tesla.Env{status: 503, body: "unavailable"}} + end + end) + + exposure = [identifier: "user_123", value: "treatment"] + + capture_log(fn -> + :ok = Client.track_exposure_event(config, "banner", exposure) + for n <- 2..1000, do: :ok = Client.track_event(config, "event_#{n}") + for n <- 1001..2000, do: :ok = Client.track_event(config, "event_#{n}") + + for _attempt <- 1..3 do + assert_receive {:holding, request, ["$flag_exposure" | _]}, 1000 + send(request, :release) + end + + # The batch is kept, but only the newest 1000 events fit the buffer, which the + # events tracked meanwhile filled up: they're sent straight away. + assert_receive {:holding, _request, ["event_1001" | _]}, 1000 + end) + + # When + :ok = Client.track_exposure_event(config, "banner", exposure) + + # Then + pid = Processor.whereis(config.environment_key) + + assert [%{event: "$flag_exposure", feature_name: "banner"}] = + :queue.to_list(:sys.get_state(pid).buffer) + end + test "closing the client stops a flush still sending when its timeout expires", %{ config: config } do