From 5f9749967ab3dfddcd4f6b2968542b10361051de Mon Sep 17 00:00:00 2001 From: Jason Stiebs Date: Fri, 23 Oct 2026 14:08:12 -0500 Subject: [PATCH 1/2] Return supervisor_unavailable instead of acquiring without the supervisor A missing singleflight registry made ensure_started_child and rehome_child run the acquisition anyway, outside deduplication, and then raise from the supervisor's missing config table. Return {:error, :supervisor_unavailable} from the singleflight, the leader's config read, the waiter's config read, and the start_child entry instead. --- CHANGELOG.md | 4 + lib/durable_server/supervisor.ex | 330 ++++++++++-------- .../supervisor_unavailable_test.exs | 110 ++++++ 3 files changed, 305 insertions(+), 139 deletions(-) create mode 100644 test/durable_server/supervisor_unavailable_test.exs diff --git a/CHANGELOG.md b/CHANGELOG.md index fd26240..1e70812 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +## Unreleased + +- 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) - Balance new child starts using the existing eligible-node ranking, considering live local capacity alongside remote heartbeat capacity instead of filling local first. Eligible local remains a candidate even when it ranks beyond the remote candidate-pool limit. Explicit local starts, restart/rehome, and sticky-placement behavior are unchanged. diff --git a/lib/durable_server/supervisor.ex b/lib/durable_server/supervisor.ex index 2553a92..daf7aca 100644 --- a/lib/durable_server/supervisor.ex +++ b/lib/durable_server/supervisor.ex @@ -787,6 +787,9 @@ defmodule DurableServer.Supervisor do complete, including internal retries. Returns `{:error, :timeout}` on expiration. Set to `:infinity` to disable. Default: `#{@default_start_child_timeout}`ms. + Returns `{:error, :supervisor_unavailable}` without attempting a start when the + local supervisor is not running or is restarting. + ## Examples # Start with init args @@ -935,8 +938,9 @@ defmodule DurableServer.Supervisor do end end - with {:ok, boot_info} <- - check_existing(supervisor, init_arg, boot_info, Keyword.get(opts, :existing, false)) do + with {:ok, config} <- __fetch_config__(supervisor), + {:ok, boot_info} <- + check_existing(config, init_arg, boot_info, Keyword.get(opts, :existing, false)) do child_spec = {module, init_arg, boot_info} # New starts rank local alongside the other nodes. Keep targeted/preloaded @@ -997,12 +1001,10 @@ defmodule DurableServer.Supervisor do end end - defp check_existing(_supervisor, _init_arg, boot_info, false), do: {:ok, boot_info} + defp check_existing(_config, _init_arg, boot_info, false), do: {:ok, boot_info} - defp check_existing(supervisor, init_arg, _boot_info, true) do + defp check_existing(config, init_arg, _boot_info, true) do key = Keyword.fetch!(init_arg, :key) - - config = __get_config__(supervisor) storage_key = config.prefix <> key case StorageBackend.get_object(config.storage_backend, storage_key, consistent: true) do @@ -2135,6 +2137,9 @@ defmodule DurableServer.Supervisor do - `{:ok, {pid, meta}}` - Process is running (either found or newly started) - `{:error, {:unreachable, pid}}` - Storage has a live lock for `pid`, but no Group metadata became reachable before the registration-race wait expired + - `{:error, :supervisor_unavailable}` - The local supervisor is not running, + is restarting, or has begun its final shutdown teardown, so no acquisition + was attempted. Retryable once the supervisor is running again. - `{:error, reason}` - Failed to start the process ## Examples @@ -2259,153 +2264,178 @@ defmodule DurableServer.Supervisor do {:ok, {pid, meta}} nil -> - {_, init_arg, _boot_info} = child_spec - local_only = Keyword.get(opts, :local_only, false) - # ensure_started_child should be single-attempt by default so hot paths - # can control retry policy at the caller boundary. - placement_timeout = Keyword.get(opts, :placement_timeout, nil) + # The singleflight claim does not keep the supervisor alive: its config + # table can disappear while this acquisition runs. + case __fetch_config__(supervisor) do + {:ok, config} -> + ensure_started_missing_child( + supervisor, + module, + key, + child_spec, + opts, + deadline_ms, + config + ) - placement_deadline_ms = - earlier_deadline(deadline_ms, deadline_after_optional_timeout(placement_timeout)) + {:error, :supervisor_unavailable} = error -> + error + end + end + end - # Try to fetch stored object to check sticky placement before attempting local start - config = __get_config__(supervisor) - storage_key = config.prefix <> key + defp ensure_started_missing_child( + supervisor, + module, + key, + child_spec, + opts, + deadline_ms, + config + ) do + {_, init_arg, _boot_info} = child_spec + local_only = Keyword.get(opts, :local_only, false) + # ensure_started_child should be single-attempt by default so hot paths + # can control retry policy at the caller boundary. + placement_timeout = Keyword.get(opts, :placement_timeout, nil) - existing = Keyword.get(opts, :existing, false) + placement_deadline_ms = + earlier_deadline(deadline_ms, deadline_after_optional_timeout(placement_timeout)) - {stored_object, sticky_placement} = - case StorageBackend.get_object( - config.storage_backend, - storage_key, - consistent: existing - ) do - {:ok, %{body: body, etag: etag}} -> - # Get augmented sticky placement (handles module config updates like :any) - augmented_placement = - __get_augmented_sticky_placement__(supervisor, module, key, body) + # Try to fetch stored object to check sticky placement before attempting local start + storage_key = config.prefix <> key + existing = Keyword.get(opts, :existing, false) - {{:ok, %{body: body, etag: etag}}, augmented_placement} + {stored_object, sticky_placement} = + case StorageBackend.get_object( + config.storage_backend, + storage_key, + consistent: existing + ) do + {:ok, %{body: body, etag: etag}} -> + # Get augmented sticky placement (handles module config updates like :any) + augmented_placement = + __get_augmented_sticky_placement__(supervisor, module, key, body) - {:error, _} -> - {nil, nil} - end + {{:ok, %{body: body, etag: etag}}, augmented_placement} - if existing and stored_object == nil do - {:error, :not_found} + {:error, _} -> + {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 - # 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 + case sticky_placement do + nil -> + # No sticky placement, proceed with normal placement. {_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} + [%{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 - - 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)} + end + end - nil -> - child_spec - 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)} - # 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" - ) + nil -> + child_spec + end - await_sticky_placement( - supervisor, - module, - key, - stored_object, - child_spec_with_boot_info, - matching_level, - placement_deadline_ms, - deadline_ms - ) + # 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" + ) - 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)) + await_sticky_placement( + supervisor, + module, + key, + stored_object, + child_spec_with_boot_info, + matching_level, + placement_deadline_ms, + 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 + {:error, reason} -> + {:error, reason} end - end + end end end @@ -2507,8 +2537,11 @@ defmodule DurableServer.Supervisor do ) {:error, :registry_unavailable} -> - # Supervisor is shutting down or the registry is already gone. - {:result, fun.()} + # The singleflight registries stop before the rest of the tree during + # shutdown and are absent while the supervisor is down or restarting. + # Running the acquisition here would bypass deduplication and then fail + # on the supervisor's missing config table. + {:result, {:error, :supervisor_unavailable}} end end @@ -2533,11 +2566,9 @@ defmodule DurableServer.Supervisor do if owner_pid == self() do :retry else - %{max_singleflight_waiters_per_key_module: max_waiters} = __get_config__(supervisor) - - case SingleflightGuard.acquire(supervisor, singleflight_key, wait_timeout_ms, max_waiters) do - {:error, :singleflight_overloaded} -> - {:result, {:error, :singleflight_overloaded}} + case acquire_singleflight_waiter_guard(supervisor, singleflight_key, wait_timeout_ms) do + {:error, reason} when reason in [:supervisor_unavailable, :singleflight_overloaded] -> + {:result, {:error, reason}} {:ok, guard_ref} -> waiter_ref = make_ref() @@ -2614,6 +2645,13 @@ defmodule DurableServer.Supervisor do ArgumentError -> :retry end + defp acquire_singleflight_waiter_guard(supervisor, singleflight_key, wait_timeout_ms) do + with {:ok, %{max_singleflight_waiters_per_key_module: max_waiters}} <- + __fetch_config__(supervisor) do + SingleflightGuard.acquire(supervisor, singleflight_key, wait_timeout_ms, max_waiters) + end + end + @doc false def __register_singleflight_waiter__( owner_registry, @@ -3846,6 +3884,20 @@ defmodule DurableServer.Supervisor do end end + @doc false + # Non-raising config read for acquisition entry points. The table is owned by + # the supervisor process, so it is absent while the supervisor is starting, + # after it exits, and between a crash and its restart. `:ets.lookup/2` raises + # ArgumentError only when the named table does not exist. + def __fetch_config__(supervisor_name) do + case :ets.lookup(ets_table_name(supervisor_name), :config) do + [{:config, config}] -> {:ok, config} + [] -> {:error, :supervisor_unavailable} + end + rescue + ArgumentError -> {:error, :supervisor_unavailable} + end + @doc false def __ets_table_name__(supervisor_name) do ets_table_name(supervisor_name) diff --git a/test/durable_server/supervisor_unavailable_test.exs b/test/durable_server/supervisor_unavailable_test.exs new file mode 100644 index 0000000..a796d45 --- /dev/null +++ b/test/durable_server/supervisor_unavailable_test.exs @@ -0,0 +1,110 @@ +defmodule DurableServer.SupervisorUnavailableTest do + @moduledoc """ + Acquisition against a supervisor that is stopped, shutting down, or has lost + its config table must return `{:error, :supervisor_unavailable}` instead of + starting children outside the singleflight or raising from missing ETS. + """ + use ExUnit.Case, async: true + import DurableServer.TestHelper + + alias DurableServer.TestCounterServer + + @moduletag :capture_log + + defp start_test_supervisor do + unique_id = "#{System.system_time(:microsecond)}_#{DurableServer.UUID.uuid4()}" + name = :"test_supervisor_#{unique_id}" + + opts = [ + name: name, + prefix: "test_#{unique_id}/", + graceful_shutdown_timeout_ms: 500, + object_store: test_object_store_opts() + ] + + pid = + start_supervised!(%{ + id: {DurableServer.Supervisor, name}, + start: {DurableServer.Supervisor, :start_link, [opts]}, + type: :supervisor + }) + + {name, pid} + end + + defp child_spec(key), do: {TestCounterServer, key: key, initial_state: %{count: 0}} + + defp unique_key, do: "unavailable-#{DurableServer.UUID.uuid4()}" + + defp local_children(name) do + name + |> DurableServer.Supervisor.get_dynamic_supervisor() + |> DynamicSupervisor.which_children() + end + + describe "after the supervisor has stopped" do + setup do + {name, _pid} = start_test_supervisor() + :ok = stop_supervised({DurableServer.Supervisor, name}) + %{name: name} + end + + test "ensure_started_child returns supervisor_unavailable", %{name: name} do + assert {:error, :supervisor_unavailable} = + DurableServer.Supervisor.ensure_started_child(name, child_spec(unique_key())) + end + + test "start_child returns supervisor_unavailable", %{name: name} do + assert {:error, :supervisor_unavailable} = + DurableServer.Supervisor.start_child(name, child_spec(unique_key())) + end + + test "rehome_child returns supervisor_unavailable", %{name: name} do + assert {:error, :supervisor_unavailable} = + DurableServer.Supervisor.rehome_child(name, child_spec(unique_key())) + end + + test "lookup reports no registered child", %{name: name} do + assert DurableServer.Supervisor.lookup(name, unique_key()) == nil + end + end + + describe "while the supervisor is shutting down" do + test "ensure_started_child does not bypass the singleflight once its registry is gone" do + {name, pid} = start_test_supervisor() + + # Shutdown stops children in reverse start order, so the singleflight + # registries disappear while the config table and DynamicSupervisor remain. + :ok = Supervisor.terminate_child(pid, :"durable_sf_waiters_#{name}") + :ok = Supervisor.terminate_child(pid, :"durable_sf_owner_#{name}") + + assert {:error, :supervisor_unavailable} = + DurableServer.Supervisor.ensure_started_child(name, child_spec(unique_key())) + + assert local_children(name) == [] + end + + test "ensure_started_child returns supervisor_unavailable when the config table disappears after the singleflight claim" do + {name, _pid} = start_test_supervisor() + + # The config table is owned by the supervisor process, so it vanishes with + # it while an acquisition that already holds the singleflight continues. + true = :ets.delete(DurableServer.Supervisor.__ets_table_name__(name)) + + assert {:error, :supervisor_unavailable} = + DurableServer.Supervisor.ensure_started_child(name, child_spec(unique_key())) + + assert local_children(name) == [] + end + + test "start_child returns supervisor_unavailable when the config table disappears" do + {name, _pid} = start_test_supervisor() + true = :ets.delete(DurableServer.Supervisor.__ets_table_name__(name)) + + assert {:error, :supervisor_unavailable} = + DurableServer.Supervisor.start_child(name, child_spec(unique_key())) + + assert local_children(name) == [] + end + end +end From 7a5626fe813c71c4b195cd7764a5c9d90b359557 Mon Sep 17 00:00:00 2001 From: Jason Stiebs Date: Fri, 23 Oct 2026 14:30:31 -0500 Subject: [PATCH 2/2] Keep fetch_config private and cover the singleflight waiter A waiter whose supervisor loses its config table now gets {:error, :supervisor_unavailable} immediately instead of retrying until the owner finishes. --- lib/durable_server/supervisor.ex | 16 +++++----- .../supervisor_unavailable_test.exs | 30 +++++++++++++++++++ 2 files changed, 37 insertions(+), 9 deletions(-) diff --git a/lib/durable_server/supervisor.ex b/lib/durable_server/supervisor.ex index daf7aca..147a0f9 100644 --- a/lib/durable_server/supervisor.ex +++ b/lib/durable_server/supervisor.ex @@ -938,7 +938,7 @@ defmodule DurableServer.Supervisor do end end - with {:ok, config} <- __fetch_config__(supervisor), + with {:ok, config} <- fetch_config(supervisor), {:ok, boot_info} <- check_existing(config, init_arg, boot_info, Keyword.get(opts, :existing, false)) do child_spec = {module, init_arg, boot_info} @@ -2266,7 +2266,7 @@ defmodule DurableServer.Supervisor do nil -> # The singleflight claim does not keep the supervisor alive: its config # table can disappear while this acquisition runs. - case __fetch_config__(supervisor) do + case fetch_config(supervisor) do {:ok, config} -> ensure_started_missing_child( supervisor, @@ -2647,7 +2647,7 @@ defmodule DurableServer.Supervisor do defp acquire_singleflight_waiter_guard(supervisor, singleflight_key, wait_timeout_ms) do with {:ok, %{max_singleflight_waiters_per_key_module: max_waiters}} <- - __fetch_config__(supervisor) do + fetch_config(supervisor) do SingleflightGuard.acquire(supervisor, singleflight_key, wait_timeout_ms, max_waiters) end end @@ -3884,12 +3884,10 @@ defmodule DurableServer.Supervisor do end end - @doc false - # Non-raising config read for acquisition entry points. The table is owned by - # the supervisor process, so it is absent while the supervisor is starting, - # after it exits, and between a crash and its restart. `:ets.lookup/2` raises - # ArgumentError only when the named table does not exist. - def __fetch_config__(supervisor_name) do + # The supervisor process owns the table, so it is absent while the supervisor + # starts, after it exits, and until it restarts. `:ets.lookup/2` raises + # ArgumentError only for a missing table. + defp fetch_config(supervisor_name) do case :ets.lookup(ets_table_name(supervisor_name), :config) do [{:config, config}] -> {:ok, config} [] -> {:error, :supervisor_unavailable} diff --git a/test/durable_server/supervisor_unavailable_test.exs b/test/durable_server/supervisor_unavailable_test.exs index a796d45..fa5b87f 100644 --- a/test/durable_server/supervisor_unavailable_test.exs +++ b/test/durable_server/supervisor_unavailable_test.exs @@ -97,6 +97,36 @@ defmodule DurableServer.SupervisorUnavailableTest do assert local_children(name) == [] end + test "ensure_started_child waiting on another owner returns supervisor_unavailable when the config table disappears" do + {name, _pid} = start_test_supervisor() + key = unique_key() + parent = self() + + # Another acquisition already holds the singleflight and is still running. + owner = + spawn_link(fn -> + {:ok, _} = + Registry.register( + :"durable_sf_owner_#{name}", + {:ensure_started_child, key, TestCounterServer}, + :singleflight_owner + ) + + send(parent, :owner_registered) + receive do: (:stop -> :ok) + end) + + assert_receive :owner_registered + true = :ets.delete(DurableServer.Supervisor.__ets_table_name__(name)) + + assert {:error, :supervisor_unavailable} = + DurableServer.Supervisor.ensure_started_child(name, child_spec(key), + timeout: 2_000 + ) + + send(owner, :stop) + end + test "start_child returns supervisor_unavailable when the config table disappears" do {name, _pid} = start_test_supervisor() true = :ets.delete(DurableServer.Supervisor.__ets_table_name__(name))