From dd04f0500b77c0b22c626b49706f061caa649d33 Mon Sep 17 00:00:00 2001 From: Chris McCord Date: Mon, 26 Oct 2026 16:20:52 -0400 Subject: [PATCH 1/3] Report a stored-state read failure as storage_unavailable, not not_found With existing: true, start_child/3 and ensure_started_child/3 read the child's stored state and treated any read error as a missing object, so a throttled or failed store response, a timeout, or a dropped connection told the caller the child didn't exist. Only the store saying the object doesn't exist is :not_found now. A read error that may pass is retried within the caller's deadline, and one that persists returns {:error, {:storage_unavailable, reason}} without starting anything. --- CHANGELOG.md | 1 + lib/durable_server/supervisor.ex | 305 +++++++++++------- .../existing_read_error_test.exs | 222 +++++++++++++ 3 files changed, 413 insertions(+), 115 deletions(-) create mode 100644 test/durable_server/existing_read_error_test.exs diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e70812..6386979 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ ## Unreleased +- Stop reporting a stored-state read failure as a missing child. `start_child/3` and `ensure_started_child/3` with `existing: true` returned `{:error, :not_found}` for any read error: a throttled or failed store response, a timeout, a dropped connection, an undecodable object. They now return `{:error, :not_found}` only when the store says the object doesn't exist. A read error that may pass is retried (3 attempts in all, with a short backoff, within the caller's `:timeout`), and one that persists returns `{:error, {:storage_unavailable, reason}}` without starting anything. Without `existing: true`, an unreadable stored state is retried the same way and then starts as before, with the child's init reading and claiming its state itself. - Return `{:error, :supervisor_unavailable}` from `ensure_started_child/3`, `start_child/3`, and `rehome_child/3` when the local supervisor is not running, is restarting, or its singleflight registries have already stopped during shutdown. Previously a missing singleflight registry made the acquisition run anyway, outside deduplication, and raise from the supervisor's missing config table. Remote placement treats the result like any other failed target and tries the next node. Graceful shutdown is unchanged: the registries stay up until the Terminator has drained children. ## 0.1.6 (2026-10-12) diff --git a/lib/durable_server/supervisor.ex b/lib/durable_server/supervisor.ex index 147a0f9..910a9da 100644 --- a/lib/durable_server/supervisor.ex +++ b/lib/durable_server/supervisor.ex @@ -237,6 +237,13 @@ defmodule DurableServer.Supervisor do @remote_placement_ready_timeout 500 @shutdown_placement_attempt_wait_timeout :timer.seconds(1) @default_placement_timeout :timer.seconds(15) + + # A stored-object read that fails for a reason that may pass (a throttled or + # failed store response, a timeout, a dropped connection) is tried this many + # times in all, within the caller's deadline, before the caller is told that + # storage is unavailable. + @stored_read_attempts 3 + @stored_read_retry_base_ms 100 @default_start_child_timeout 5_000 @already_started_registration_poll_ms 100 @default_discovery_interval_ms 60_000 @@ -779,6 +786,11 @@ defmodule DurableServer.Supervisor do - `:max_placement_retries` - Maximum number of remote nodes to try per placement round, in addition to local. Set to `0` for local-only placement. Default: `3`. Ignored when `local_only: true`. + - `:existing` - When `true`, start the child only from its stored state. + Returns `{:error, :not_found}` when the store says no state exists, and + `{:error, {:storage_unavailable, reason}}` when the stored state could not + be read, after retrying a read error that may pass (#{@stored_read_attempts} + attempts in all, within `:timeout`). Default: `false`. - `:placement_timeout` - Maximum time in milliseconds to keep retrying placement. If all placement attempts fail, the caller retries with fresh eligible nodes every #{@placement_retry_interval}ms until the deadline. Useful during rolling deploys when @@ -940,7 +952,13 @@ defmodule DurableServer.Supervisor do with {:ok, config} <- fetch_config(supervisor), {:ok, boot_info} <- - check_existing(config, init_arg, boot_info, Keyword.get(opts, :existing, false)) do + check_existing( + config, + init_arg, + boot_info, + Keyword.get(opts, :existing, false), + caller_deadline_ms + ) do child_spec = {module, init_arg, boot_info} # New starts rank local alongside the other nodes. Keep targeted/preloaded @@ -1001,18 +1019,64 @@ defmodule DurableServer.Supervisor do end end - defp check_existing(_config, _init_arg, boot_info, false), do: {:ok, boot_info} + defp check_existing(_config, _init_arg, boot_info, false, _deadline_ms), do: {:ok, boot_info} - defp check_existing(config, init_arg, _boot_info, true) do + defp check_existing(config, init_arg, _boot_info, true, deadline_ms) do key = Keyword.fetch!(init_arg, :key) storage_key = config.prefix <> key - case StorageBackend.get_object(config.storage_backend, storage_key, consistent: true) do + case read_stored_object(config, storage_key, true, deadline_ms) do {:ok, %{body: body, etag: etag}} -> {:ok, preloaded_boot_info(body, etag)} - {:error, _} -> + :not_found -> {:error, :not_found} + + {:error, reason} -> + {:error, {:storage_unavailable, reason}} + end + end + + # Reads a child's stored object. Only the store saying the object doesn't + # exist is `:not_found`. Any other failure is retried while it may pass and + # the caller's deadline allows, then returned as it is: it says nothing about + # whether the object exists. + defp read_stored_object(config, storage_key, consistent, deadline_ms, attempt \\ 1) do + case StorageBackend.get_object(config.storage_backend, storage_key, consistent: consistent) do + {:ok, %{body: _body, etag: _etag}} = ok -> + ok + + {:error, :not_found} -> + :not_found + + {:error, reason} -> + delay_ms = + @stored_read_retry_base_ms * attempt + :rand.uniform(@stored_read_retry_base_ms) + + if attempt < @stored_read_attempts and retryable_read_error?(reason) and + retry_fits_deadline?(deadline_ms, delay_ms) do + Process.sleep(delay_ms) + read_stored_object(config, storage_key, consistent, deadline_ms, attempt + 1) + else + {:error, reason} + end + end + end + + # The object store answers any failed response but a 404 with :bad_gateway. + defp retryable_read_error?(reason) + when reason in [:bad_gateway, :timeout, :closed, :econnrefused, :econnreset], + do: true + + defp retryable_read_error?(%Req.TransportError{}), do: true + defp retryable_read_error?(%Mint.TransportError{}), do: true + defp retryable_read_error?(%Mint.HTTPError{}), do: true + defp retryable_read_error?(_reason), do: false + + defp retry_fits_deadline?(deadline_ms, delay_ms) do + case remaining_timeout_ms(deadline_ms) do + :infinity -> true + remaining_ms -> remaining_ms > delay_ms end end @@ -2124,6 +2188,11 @@ defmodule DurableServer.Supervisor do - `:max_placement_retries` - Maximum number of remote nodes to try per placement round, in addition to local. Set to `0` for local-only placement. Default: `3`. Ignored when `local_only: true`. + - `:existing` - When `true`, start the child only from its stored state. + Returns `{:error, :not_found}` when the store says no state exists, and + `{:error, {:storage_unavailable, reason}}` when the stored state could not + be read, after retrying a read error that may pass (#{@stored_read_attempts} + attempts in all, within `:timeout`). Default: `false`. - `:placement_timeout` - Maximum time in milliseconds to keep retrying placement. When set, if all placement attempts fail, retries with fresh eligible nodes every #{@placement_retry_interval}ms until the deadline. Default: `nil` (no retry). @@ -2306,12 +2375,10 @@ defmodule DurableServer.Supervisor do storage_key = config.prefix <> key existing = Keyword.get(opts, :existing, false) + read = read_stored_object(config, storage_key, existing, deadline_ms) + {stored_object, sticky_placement} = - case StorageBackend.get_object( - config.storage_backend, - storage_key, - consistent: existing - ) do + case read do {:ok, %{body: body, etag: etag}} -> # Get augmented sticky placement (handles module config updates like :any) augmented_placement = @@ -2319,123 +2386,131 @@ defmodule DurableServer.Supervisor do {{:ok, %{body: body, etag: etag}}, augmented_placement} - {:error, _} -> + # Without existing: true, a child whose state couldn't be read starts + # as before: its init reads and claims the stored state itself. + _missing_or_unreadable -> {nil, nil} end - if existing and stored_object == nil do - {:error, :not_found} - else - # Check if we should respect sticky placement and skip local start - # Also track matching_level for time-gated fallback when remote placement fails - # Also track if local node matches sticky level 0 with a SPECIFIC env var (for disk check bypass) - # When local_only: true, never skip local — ignore sticky placement preferences - {should_skip_local, is_sticky_local, matching_level} = - if local_only do - {_should_skip_local = false, _is_sticky_local = false, _matching_level = nil} - else - case sticky_placement do - nil -> - # No sticky placement, proceed with normal placement. - {_should_skip_local = false, _is_sticky_local = false, _matching_level = nil} - - [%{env_var: :any, value: :any} | _] -> - # First level is :any, so local node is acceptable but we don't know - # if data is specifically here (could have been on any node) - {_should_skip_local = false, _is_sticky_local = false, _matching_level = 0} - - placement -> - # Have specific sticky placement (first element is not :any) - # Check if local node matches - env_var_names = - DurableServer.Supervisor.collect_sticky_placement_env_vars(supervisor) - - my_env_vars = - env_var_names - |> Enum.map(fn var_name -> {var_name, System.get_env(var_name)} end) - |> Enum.into(%{}) - - # Check if we match any level (0 = exact, 1 = less specific, etc.) - my_matching_level = - Enum.find_index(placement, fn preference -> - case preference do - %{env_var: :any, value: :any} -> - true - - %{env_var: env_var, value: expected_value} -> - Map.get(my_env_vars, env_var) == expected_value - - _ -> - false - end - end) - - # Skip local start only if we don't match level 0 (exact match) - # This ensures servers stay on their sticky placement node for specific matches - if my_matching_level == 0 do - # Level 0 match with specific env var - use local, bypass disk check - # (we know it's specific because :any at level 0 is handled above) - {_should_skip_local = false, _is_sticky_local = true, my_matching_level} - else - # Level > 0 match or nil (no match) - skip local to try remote first - {_should_skip_local = true, _is_sticky_local = false, my_matching_level} - end + case {existing, read} do + {true, :not_found} -> + {:error, :not_found} + + {true, {:error, reason}} -> + {:error, {:storage_unavailable, reason}} + + _start -> + # Check if we should respect sticky placement and skip local start + # Also track matching_level for time-gated fallback when remote placement fails + # Also track if local node matches sticky level 0 with a SPECIFIC env var (for disk check bypass) + # When local_only: true, never skip local — ignore sticky placement preferences + {should_skip_local, is_sticky_local, matching_level} = + if local_only do + {_should_skip_local = false, _is_sticky_local = false, _matching_level = nil} + else + case sticky_placement do + nil -> + # No sticky placement, proceed with normal placement. + {_should_skip_local = false, _is_sticky_local = false, _matching_level = nil} + + [%{env_var: :any, value: :any} | _] -> + # First level is :any, so local node is acceptable but we don't know + # if data is specifically here (could have been on any node) + {_should_skip_local = false, _is_sticky_local = false, _matching_level = 0} + + placement -> + # Have specific sticky placement (first element is not :any) + # Check if local node matches + env_var_names = + DurableServer.Supervisor.collect_sticky_placement_env_vars(supervisor) + + my_env_vars = + env_var_names + |> Enum.map(fn var_name -> {var_name, System.get_env(var_name)} end) + |> Enum.into(%{}) + + # Check if we match any level (0 = exact, 1 = less specific, etc.) + my_matching_level = + Enum.find_index(placement, fn preference -> + case preference do + %{env_var: :any, value: :any} -> + true + + %{env_var: env_var, value: expected_value} -> + Map.get(my_env_vars, env_var) == expected_value + + _ -> + false + end + end) + + # Skip local start only if we don't match level 0 (exact match) + # This ensures servers stay on their sticky placement node for specific matches + if my_matching_level == 0 do + # Level 0 match with specific env var - use local, bypass disk check + # (we know it's specific because :any at level 0 is handled above) + {_should_skip_local = false, _is_sticky_local = true, my_matching_level} + else + # Level > 0 match or nil (no match) - skip local to try remote first + {_should_skip_local = true, _is_sticky_local = false, my_matching_level} + end + end end - end - child_spec_with_boot_info = - case stored_object do - {:ok, %{body: body, etag: etag}} -> - {module, init_arg, preloaded_boot_info(body, etag, is_sticky_local: is_sticky_local)} + child_spec_with_boot_info = + case stored_object do + {:ok, %{body: body, etag: etag}} -> + {module, init_arg, + preloaded_boot_info(body, etag, is_sticky_local: is_sticky_local)} - nil -> - child_spec - end + nil -> + child_spec + end - # If we should skip local due to sticky placement, go straight to remote placement - cond do - should_skip_local -> - Logger.info( - "Skipping local start for #{key} due to sticky placement mismatch (level=#{inspect(matching_level)}), trying remote placement" - ) + # If we should skip local due to sticky placement, go straight to remote placement + cond do + should_skip_local -> + Logger.info( + "Skipping local start for #{key} due to sticky placement mismatch (level=#{inspect(matching_level)}), trying remote placement" + ) - await_sticky_placement( - supervisor, - module, - key, - stored_object, - child_spec_with_boot_info, - matching_level, - placement_deadline_ms, - deadline_ms - ) + await_sticky_placement( + supervisor, + module, + key, + stored_object, + child_spec_with_boot_info, + matching_level, + placement_deadline_ms, + deadline_ms + ) - true -> - # Rank new children; persisted children retain their local/sticky path. - start_opts = - opts - |> Keyword.delete(:existing) - |> Keyword.put_new(:placement_timeout, nil) - |> Keyword.put(:timeout, timeout_option(deadline_ms)) - - case __start_child__( - supervisor, - child_spec_with_boot_info, - start_opts - ) do - {:ok, {pid, meta}} -> - {:ok, {pid, meta}} + true -> + # Rank new children; persisted children retain their local/sticky path. + start_opts = + opts + |> Keyword.delete(:existing) + |> Keyword.put_new(:placement_timeout, nil) + |> Keyword.put(:timeout, timeout_option(deadline_ms)) + + case __start_child__( + supervisor, + child_spec_with_boot_info, + start_opts + ) do + {:ok, {pid, meta}} -> + {:ok, {pid, meta}} - {:error, {:already_started, other}} -> - normalize_already_started_result(supervisor, key, other, deadline_ms) + {:error, {:already_started, other}} -> + normalize_already_started_result(supervisor, key, other, deadline_ms) - :ignore -> - :ignore + :ignore -> + :ignore - {:error, reason} -> - {:error, reason} - end - end + {:error, reason} -> + {:error, reason} + end + end end end diff --git a/test/durable_server/existing_read_error_test.exs b/test/durable_server/existing_read_error_test.exs new file mode 100644 index 0000000..a27658a --- /dev/null +++ b/test/durable_server/existing_read_error_test.exs @@ -0,0 +1,222 @@ +defmodule DurableServer.ExistingReadErrorTest do + use ExUnit.Case, async: false + + alias DurableServer.StorageBackend + alias DurableServer.TestCounterServer + + # An in-memory backend whose reads can be made to fail: `fail_reads/3` makes + # the next `count` reads of a key return `{:error, reason}`, and every read + # of a key is counted. + defmodule FlakyReadBackend do + @behaviour StorageBackend + + @impl true + def init_backend(opts) do + opts = Map.new(opts) + + {:ok, + %{ + state: %{table: Map.fetch!(opts, :table)}, + defaults: %{ + heartbeat_tracking_mode: :poll, + discovery_interval_ms: 60_000, + heartbeat_interval_ms: 10_000, + heartbeat_reconcile_interval_ms: 10_000 + } + }} + end + + @impl true + def ensure_ready(_state), do: :ok + + @impl true + def get_object(%{table: table}, key, _opts) do + :ets.update_counter(table, {:reads, key}, 1, {{:reads, key}, 0}) + + case :ets.lookup(table, {:fail, key}) do + [{_, reason, count}] when count > 0 -> + :ets.insert(table, {{:fail, key}, reason, count - 1}) + {:error, reason} + + _ -> + case :ets.lookup(table, {:object, key}) do + [{_, object}] -> {:ok, object} + [] -> {:error, :not_found} + end + end + end + + @impl true + def list_all_objects_stream(%{table: table}, prefix, _opts) do + table + |> :ets.match({{:object, :"$1"}, %{etag: :"$2"}}) + |> Stream.filter(fn [key, _etag] -> String.starts_with?(key, prefix) end) + |> Stream.map(fn [key, etag] -> %{key: key, etag: etag} end) + end + + @impl true + def put_object(%{table: table}, key, data, _opts) do + object = %{body: data, etag: next_etag()} + :ets.insert(table, {{:object, key}, object}) + {:ok, object} + end + + @impl true + def delete_object(%{table: table}, key) do + case :ets.take(table, {:object, key}) do + [_object] -> :ok + [] -> {:error, :not_found} + end + end + + @impl true + def try_claim(%{table: table}, key, body) do + etag = next_etag() + + if :ets.insert_new(table, {{:object, key}, %{body: body, etag: etag}}), + do: {:ok, {:claimed, etag}}, + else: {:error, :taken} + end + + @impl true + def update_object(%{table: table} = state, key, update_fn, _opts) do + case :ets.lookup(table, {:object, key}) do + [{_, object}] -> + with {:ok, new_body} <- update_fn.(object), do: put_object(state, key, new_body, []) + + [] -> + {:error, :not_found} + end + end + + @impl true + def encode(_state, data), do: {:ok, data} + + @impl true + def decode(_state, data), do: {:ok, data} + + def fail_reads(table, key, reason, count), + do: :ets.insert(table, {{:fail, key}, reason, count}) + + def reads(table, key) do + case :ets.lookup(table, {:reads, key}) do + [{_, count}] -> count + [] -> 0 + end + end + + defp next_etag, + do: Integer.to_string(System.unique_integer([:positive, :monotonic])) + end + + setup do + # Owned by a holder that stops after the supervisor, so the backend's + # table outlives the supervisor's shutdown writes. + holder = start_supervised!({Agent, fn -> :ets.new(__MODULE__, [:set, :public]) end}) + table = Agent.get(holder, & &1) + name = :"existing_read_error_#{System.unique_integer([:positive, :monotonic])}" + prefix = "existing_read_error/#{System.unique_integer([:positive, :monotonic])}/" + + start_supervised!( + {DurableServer.Supervisor, + [ + name: name, + prefix: prefix, + backend: {FlakyReadBackend, table: table}, + graceful_shutdown_timeout_ms: 500 + ]} + ) + + %{supervisor: name, prefix: prefix, table: table} + end + + # Starts, syncs, and stops a server for `key`, so its state is stored. + defp store(supervisor, key) do + {:ok, {pid, _meta}} = + DurableServer.Supervisor.start_child( + supervisor, + {TestCounterServer, key: key, initial_state: %{count: 0}} + ) + + 1 = GenServer.call(pid, :increment_and_sync) + ref = Process.monitor(pid) + :ok = DurableServer.Supervisor.terminate_child(supervisor, key) + assert_receive {:DOWN, ^ref, :process, ^pid, _reason}, 5_000 + end + + defp child(key), do: {TestCounterServer, key: key, initial_state: %{count: 0}} + + for {fun, label} <- [ensure_started_child: "ensure_started_child", start_child: "start_child"] do + describe "#{label} with existing: true" do + test "retries a retryable read error and starts the stored server", ctx do + key = "retry-#{unquote(fun)}" + store(ctx.supervisor, key) + storage_key = ctx.prefix <> key + reads = FlakyReadBackend.reads(ctx.table, storage_key) + FlakyReadBackend.fail_reads(ctx.table, storage_key, :bad_gateway, 1) + + assert {:ok, {pid, _meta}} = + apply(DurableServer.Supervisor, unquote(fun), [ + ctx.supervisor, + child(key), + [existing: true] + ]) + + assert GenServer.call(pid, :get_count) == 1 + assert FlakyReadBackend.reads(ctx.table, storage_key) - reads >= 2 + end + + test "a read that keeps failing is storage_unavailable, not not_found", ctx do + key = "unavailable-#{unquote(fun)}" + store(ctx.supervisor, key) + storage_key = ctx.prefix <> key + reads = FlakyReadBackend.reads(ctx.table, storage_key) + reason = %Req.TransportError{reason: :timeout} + FlakyReadBackend.fail_reads(ctx.table, storage_key, reason, 1_000) + + assert {:error, {:storage_unavailable, ^reason}} = + apply(DurableServer.Supervisor, unquote(fun), [ + ctx.supervisor, + child(key), + [existing: true] + ]) + + # Retried, and nothing was started for the key. + assert FlakyReadBackend.reads(ctx.table, storage_key) - reads >= 2 + assert DurableServer.Supervisor.lookup(ctx.supervisor, key) == nil + end + + test "an error that isn't retryable is storage_unavailable at once", ctx do + key = "corrupt-#{unquote(fun)}" + store(ctx.supervisor, key) + storage_key = ctx.prefix <> key + reads = FlakyReadBackend.reads(ctx.table, storage_key) + reason = {:invalid_stored_state, :bad_meta} + FlakyReadBackend.fail_reads(ctx.table, storage_key, reason, 1_000) + + assert {:error, {:storage_unavailable, ^reason}} = + apply(DurableServer.Supervisor, unquote(fun), [ + ctx.supervisor, + child(key), + [existing: true] + ]) + + assert FlakyReadBackend.reads(ctx.table, storage_key) - reads == 1 + end + + test "a definite miss is not_found, read once", ctx do + key = "missing-#{unquote(fun)}" + storage_key = ctx.prefix <> key + + assert {:error, :not_found} = + apply(DurableServer.Supervisor, unquote(fun), [ + ctx.supervisor, + child(key), + [existing: true] + ]) + + assert FlakyReadBackend.reads(ctx.table, storage_key) == 1 + end + end + end +end From 96cd3819281d06c52df8a2863f76cbc376690aef Mon Sep 17 00:00:00 2001 From: Chris McCord Date: Mon, 26 Oct 2026 16:43:43 -0400 Subject: [PATCH 2/3] Tell a missing server from an unreadable one in get_server_info get_server_info/2 read eventually consistent and returned :not_found for any read error. It now retries a read error that may pass, returns {:error, {:storage_unavailable, reason}} when the state still can't be read, and takes consistent: true for callers about to act on a miss. --- CHANGELOG.md | 1 + lib/durable_server/supervisor.ex | 62 ++++++++++++++----- .../existing_read_error_test.exs | 60 +++++++++++++++++- 3 files changed, 106 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6386979..745c128 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ ## Unreleased - Stop reporting a stored-state read failure as a missing child. `start_child/3` and `ensure_started_child/3` with `existing: true` returned `{:error, :not_found}` for any read error: a throttled or failed store response, a timeout, a dropped connection, an undecodable object. They now return `{:error, :not_found}` only when the store says the object doesn't exist. A read error that may pass is retried (3 attempts in all, with a short backoff, within the caller's `:timeout`), and one that persists returns `{:error, {:storage_unavailable, reason}}` without starting anything. Without `existing: true`, an unreadable stored state is retried the same way and then starts as before, with the child's init reading and claiming its state itself. +- `get_server_info/3` (was `/2`) had the same problem: any read error, from an eventually consistent read, came back as `{:error, :not_found}`. It now retries a read error that may pass and returns `{:error, {:storage_unavailable, reason}}` when the state still can't be read, keeping `{:error, :not_found}` for the store saying no state exists. A new `consistent: true` option reads the store's consistent view, for callers about to act on a miss. Callers that match only `{:ok, _}` and `{:error, :not_found}` must handle the new error. - Return `{:error, :supervisor_unavailable}` from `ensure_started_child/3`, `start_child/3`, and `rehome_child/3` when the local supervisor is not running, is restarting, or its singleflight registries have already stopped during shutdown. Previously a missing singleflight registry made the acquisition run anyway, outside deduplication, and raise from the supervisor's missing config table. Remote placement treats the result like any other failed target and tries the next node. Graceful shutdown is unchanged: the registries stay up until the Terminator has drained children. ## 0.1.6 (2026-10-12) diff --git a/lib/durable_server/supervisor.ex b/lib/durable_server/supervisor.ex index 910a9da..4dad7f0 100644 --- a/lib/durable_server/supervisor.ex +++ b/lib/durable_server/supervisor.ex @@ -472,15 +472,31 @@ defmodule DurableServer.Supervisor do iex> DurableServer.Supervisor.get_server_info(MyDurableSup, "nonexistent") {:error, :not_found} + `{:error, :not_found}` means the store says no state exists. When the state + could not be read, after retrying a read error that may pass + (#{@stored_read_attempts} attempts in all), it returns + `{:error, {:storage_unavailable, reason}}`, which says nothing about whether + the server exists. + + ## Options + + - `:consistent` - Read from the store's consistent view rather than the + nearest replica. An eventually consistent read can miss state written + moments ago, so use `true` before acting on a miss. Default: `false`. """ - def get_server_info(sup_name, key) when is_atom(sup_name) and is_binary(key) do + def get_server_info(sup_name, key, opts \\ []) when is_atom(sup_name) and is_binary(key) do + opts = Keyword.validate!(opts, consistent: false) %{storage_backend: storage_backend, prefix: prefix} = __get_config__(sup_name) - case DurableServer.fetch_stored_state( - storage_backend, - %{key: key, prefix: prefix}, - consistent: false - ) do + fetch = fn -> + DurableServer.fetch_stored_state( + storage_backend, + %{key: key, prefix: prefix}, + consistent: Keyword.fetch!(opts, :consistent) + ) + end + + case retry_read(fetch, nil) do {:ok, %DurableServer.StoredState{meta: meta, state: user_state, vsn: vsn}} -> # Check if server is currently running {pid, running} = @@ -507,8 +523,11 @@ defmodule DurableServer.Supervisor do {:ok, info} - {:error, _reason} -> + {:error, :not_found} -> {:error, :not_found} + + {:error, reason} -> + {:error, {:storage_unavailable, reason}} end end @@ -1041,25 +1060,36 @@ defmodule DurableServer.Supervisor do # exist is `:not_found`. Any other failure is retried while it may pass and # the caller's deadline allows, then returned as it is: it says nothing about # whether the object exists. - defp read_stored_object(config, storage_key, consistent, deadline_ms, attempt \\ 1) do - case StorageBackend.get_object(config.storage_backend, storage_key, consistent: consistent) do - {:ok, %{body: _body, etag: _etag}} = ok -> - ok + defp read_stored_object(config, storage_key, consistent, deadline_ms) do + read = fn -> + StorageBackend.get_object(config.storage_backend, storage_key, consistent: consistent) + end - {:error, :not_found} -> - :not_found + case retry_read(read, deadline_ms) do + {:ok, %{body: _body, etag: _etag}} = ok -> ok + {:error, :not_found} -> :not_found + {:error, reason} -> {:error, reason} + end + end - {:error, reason} -> + # Runs `read` again while it fails for a reason that may pass and the + # deadline (`nil` for none) leaves room for the backoff. + defp retry_read(read, deadline_ms, attempt \\ 1) do + case read.() do + {:error, reason} = error when reason != :not_found -> delay_ms = @stored_read_retry_base_ms * attempt + :rand.uniform(@stored_read_retry_base_ms) if attempt < @stored_read_attempts and retryable_read_error?(reason) and retry_fits_deadline?(deadline_ms, delay_ms) do Process.sleep(delay_ms) - read_stored_object(config, storage_key, consistent, deadline_ms, attempt + 1) + retry_read(read, deadline_ms, attempt + 1) else - {:error, reason} + error end + + result -> + result end end diff --git a/test/durable_server/existing_read_error_test.exs b/test/durable_server/existing_read_error_test.exs index a27658a..02ccaeb 100644 --- a/test/durable_server/existing_read_error_test.exs +++ b/test/durable_server/existing_read_error_test.exs @@ -30,8 +30,9 @@ defmodule DurableServer.ExistingReadErrorTest do def ensure_ready(_state), do: :ok @impl true - def get_object(%{table: table}, key, _opts) do + def get_object(%{table: table}, key, opts) do :ets.update_counter(table, {:reads, key}, 1, {{:reads, key}, 0}) + :ets.insert(table, {{:read_opts, key}, opts}) case :ets.lookup(table, {:fail, key}) do [{_, reason, count}] when count > 0 -> @@ -105,6 +106,13 @@ defmodule DurableServer.ExistingReadErrorTest do end end + def read_opts(table, key) do + case :ets.lookup(table, {:read_opts, key}) do + [{_, opts}] -> opts + [] -> nil + end + end + defp next_etag, do: Integer.to_string(System.unique_integer([:positive, :monotonic])) end @@ -219,4 +227,54 @@ defmodule DurableServer.ExistingReadErrorTest do end end end + + describe "get_server_info" do + test "retries a retryable read error", ctx do + key = "info-retry" + store(ctx.supervisor, key) + storage_key = ctx.prefix <> key + reads = FlakyReadBackend.reads(ctx.table, storage_key) + FlakyReadBackend.fail_reads(ctx.table, storage_key, :bad_gateway, 1) + + assert {:ok, %{key: ^key, user_state: user_state}} = + DurableServer.Supervisor.get_server_info(ctx.supervisor, key) + + assert user_state in [%{count: 1}, %{"count" => 1}] + assert FlakyReadBackend.reads(ctx.table, storage_key) - reads == 2 + end + + test "a read that keeps failing is storage_unavailable, not not_found", ctx do + key = "info-unavailable" + store(ctx.supervisor, key) + storage_key = ctx.prefix <> key + reason = %Req.TransportError{reason: :closed} + FlakyReadBackend.fail_reads(ctx.table, storage_key, reason, 1_000) + + assert {:error, {:storage_unavailable, ^reason}} = + DurableServer.Supervisor.get_server_info(ctx.supervisor, key) + end + + test "a definite miss is not_found, read once", ctx do + storage_key = ctx.prefix <> "info-missing" + + assert {:error, :not_found} = + DurableServer.Supervisor.get_server_info(ctx.supervisor, "info-missing") + + assert FlakyReadBackend.reads(ctx.table, storage_key) == 1 + end + + test "reads eventually consistent by default, or consistent on request", ctx do + key = "info-consistent" + store(ctx.supervisor, key) + storage_key = ctx.prefix <> key + + assert {:ok, _info} = DurableServer.Supervisor.get_server_info(ctx.supervisor, key) + assert FlakyReadBackend.read_opts(ctx.table, storage_key)[:consistent] == false + + assert {:ok, _info} = + DurableServer.Supervisor.get_server_info(ctx.supervisor, key, consistent: true) + + assert FlakyReadBackend.read_opts(ctx.table, storage_key)[:consistent] == true + end + end end From f3166ba0697cd0ff8f59772557a2c4691a9963d5 Mon Sep 17 00:00:00 2001 From: Chris McCord Date: Mon, 26 Oct 2026 21:07:22 -0400 Subject: [PATCH 3/3] Read get_server_info consistent by default A caller acts on what get_server_info says, and an eventually consistent read can miss state written moments ago. Read the consistent view unless the caller passes consistent: false, as stream_all_server_info/1 does for its listing, which is eventually consistent already. --- CHANGELOG.md | 2 +- lib/durable_server/supervisor.ex | 13 ++++++++----- test/durable_server/existing_read_error_test.exs | 14 ++++++++++---- 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 745c128..b4a2152 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,7 @@ ## Unreleased - Stop reporting a stored-state read failure as a missing child. `start_child/3` and `ensure_started_child/3` with `existing: true` returned `{:error, :not_found}` for any read error: a throttled or failed store response, a timeout, a dropped connection, an undecodable object. They now return `{:error, :not_found}` only when the store says the object doesn't exist. A read error that may pass is retried (3 attempts in all, with a short backoff, within the caller's `:timeout`), and one that persists returns `{:error, {:storage_unavailable, reason}}` without starting anything. Without `existing: true`, an unreadable stored state is retried the same way and then starts as before, with the child's init reading and claiming its state itself. -- `get_server_info/3` (was `/2`) had the same problem: any read error, from an eventually consistent read, came back as `{:error, :not_found}`. It now retries a read error that may pass and returns `{:error, {:storage_unavailable, reason}}` when the state still can't be read, keeping `{:error, :not_found}` for the store saying no state exists. A new `consistent: true` option reads the store's consistent view, for callers about to act on a miss. Callers that match only `{:ok, _}` and `{:error, :not_found}` must handle the new error. +- `get_server_info/3` (was `/2`) had the same problem, and read eventually consistent, so it could also miss state written moments ago: any read error or stale miss came back as `{:error, :not_found}`. It now reads the store's consistent view by default (`consistent: false` opts back into an eventually consistent read; `stream_all_server_info/1` uses it), retries a read error that may pass, and returns `{:error, {:storage_unavailable, reason}}` when the state still can't be read, keeping `{:error, :not_found}` for the store saying no state exists. Callers that match only `{:ok, _}` and `{:error, :not_found}` must handle the new error. - Return `{:error, :supervisor_unavailable}` from `ensure_started_child/3`, `start_child/3`, and `rehome_child/3` when the local supervisor is not running, is restarting, or its singleflight registries have already stopped during shutdown. Previously a missing singleflight registry made the acquisition run anyway, outside deduplication, and raise from the supervisor's missing config table. Remote placement treats the result like any other failed target and tries the next node. Graceful shutdown is unchanged: the registries stay up until the Terminator has drained children. ## 0.1.6 (2026-10-12) diff --git a/lib/durable_server/supervisor.ex b/lib/durable_server/supervisor.ex index 4dad7f0..9c38b36 100644 --- a/lib/durable_server/supervisor.ex +++ b/lib/durable_server/supervisor.ex @@ -480,12 +480,13 @@ defmodule DurableServer.Supervisor do ## Options - - `:consistent` - Read from the store's consistent view rather than the - nearest replica. An eventually consistent read can miss state written - moments ago, so use `true` before acting on a miss. Default: `false`. + - `:consistent` - Read from the store's consistent view. With `false`, + the read is eventually consistent: cheaper, but it can miss state written + moments ago, so a caller that acts on a miss shouldn't use it. Default: + `true`. """ def get_server_info(sup_name, key, opts \\ []) when is_atom(sup_name) and is_binary(key) do - opts = Keyword.validate!(opts, consistent: false) + opts = Keyword.validate!(opts, consistent: true) %{storage_backend: storage_backend, prefix: prefix} = __get_config__(sup_name) fetch = fn -> @@ -560,7 +561,9 @@ defmodule DurableServer.Supervisor do |> Stream.reject(fn %{key: key} -> String.contains?(key, "/__nodes/") end) |> Stream.map(fn %{key: storage_key} -> key = String.trim_leading(storage_key, prefix) - get_server_info(sup_name, key) + # The listing is eventually consistent already; a consistent read per + # entry would only add load. + get_server_info(sup_name, key, consistent: false) end) |> Stream.filter(fn {:ok, _info} -> true diff --git a/test/durable_server/existing_read_error_test.exs b/test/durable_server/existing_read_error_test.exs index 02ccaeb..92730ba 100644 --- a/test/durable_server/existing_read_error_test.exs +++ b/test/durable_server/existing_read_error_test.exs @@ -263,18 +263,24 @@ defmodule DurableServer.ExistingReadErrorTest do assert FlakyReadBackend.reads(ctx.table, storage_key) == 1 end - test "reads eventually consistent by default, or consistent on request", ctx do + test "reads consistent by default, or eventually consistent on request", ctx do key = "info-consistent" store(ctx.supervisor, key) storage_key = ctx.prefix <> key assert {:ok, _info} = DurableServer.Supervisor.get_server_info(ctx.supervisor, key) - assert FlakyReadBackend.read_opts(ctx.table, storage_key)[:consistent] == false + assert FlakyReadBackend.read_opts(ctx.table, storage_key)[:consistent] == true assert {:ok, _info} = - DurableServer.Supervisor.get_server_info(ctx.supervisor, key, consistent: true) + DurableServer.Supervisor.get_server_info(ctx.supervisor, key, consistent: false) - assert FlakyReadBackend.read_opts(ctx.table, storage_key)[:consistent] == true + assert FlakyReadBackend.read_opts(ctx.table, storage_key)[:consistent] == false + + # A full listing reads each entry eventually consistent. + assert [%{key: ^key}] = + Enum.to_list(DurableServer.Supervisor.stream_all_server_info(ctx.supervisor)) + + assert FlakyReadBackend.read_opts(ctx.table, storage_key)[:consistent] == false end end end