From e95432cf820f4804cf5f6f3b0bc77736f6f32bb7 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sun, 25 Oct 2026 14:31:38 -0400 Subject: [PATCH 1/2] test(subscriptions): show a failed repeated claim gives up a lock the owner still holds Signed-off-by: Yordis Prieto --- test/advisory_locks_test.exs | 67 ++++++++++++++++++++++++++++++++++-- 1 file changed, 64 insertions(+), 3 deletions(-) diff --git a/test/advisory_locks_test.exs b/test/advisory_locks_test.exs index b1975c8a..43444d31 100644 --- a/test/advisory_locks_test.exs +++ b/test/advisory_locks_test.exs @@ -11,9 +11,7 @@ defmodule EventStore.AdvisoryLocksTest do @monitor TestEventStore.EventStore.AdvisoryLocks.Postgrex.EventStore.MonitoredServer setup do - postgrex_config = Config.parsed(TestEventStore, :eventstore) |> Config.default_postgrex_opts() - - conn = start_supervised!({Postgrex, postgrex_config}) + conn = start_supervised!({Postgrex, postgrex_config()}) [conn: conn] end @@ -168,6 +166,65 @@ defmodule EventStore.AdvisoryLocksTest do Storage.Lock.try_acquire_exclusive_lock(conn, held_id, schema: schema) end + test "should keep the lock held when a repeated claim cannot wait for a table lock", + context do + %{conn: conn, schema: schema} = context + %{subscription_id: subscription_id} = create_subscription(context) + + {:ok, %AdvisoryLocks.Lease{}} = AdvisoryLocks.try_subscription_lock(@locks, subscription_id) + + table_lock = lock_subscriptions_table(context) + + try do + assert {:error, %Postgrex.Error{postgres: %{code: :lock_not_available}}} = + AdvisoryLocks.try_subscription_lock(@locks, subscription_id, 1_000) + after + release_table_lock(table_lock) + end + + assert {:error, :lock_already_taken} = + Storage.Lock.try_acquire_exclusive_lock(conn, subscription_id, schema: schema) + end + + test "should keep the lock held when a repeated claim is cancelled while it waits", context do + %{conn: conn, schema: schema} = context + %{subscription_id: subscription_id} = create_subscription(context) + + {:ok, %AdvisoryLocks.Lease{}} = AdvisoryLocks.try_subscription_lock(@locks, subscription_id) + + lock_backend_pid = backend_pid(@conn) + + canceller = start_supervised!({Postgrex, postgrex_config()}, id: :canceller) + + table_lock = lock_subscriptions_table(context) + + try do + cancel = + Task.async(fn -> + Wait.until(fn -> + assert %Postgrex.Result{rows: [["Lock"]]} = + Postgrex.query!( + canceller, + "SELECT wait_event_type FROM pg_stat_activity WHERE pid = $1", + [lock_backend_pid] + ) + end) + + Postgrex.query!(canceller, "SELECT pg_cancel_backend($1)", [lock_backend_pid]) + end) + + assert {:error, %Postgrex.Error{postgres: %{code: :query_canceled}}} = + AdvisoryLocks.try_subscription_lock(@locks, subscription_id, 10_000) + + assert %Postgrex.Result{rows: [[true]]} = Task.await(cancel) + after + release_table_lock(table_lock) + end + + assert {:error, :lock_already_taken} = + Storage.Lock.try_acquire_exclusive_lock(conn, subscription_id, schema: schema) + end + test "should fail to acquire the lock of a subscription that does not exist" do assert {:error, :subscription_not_found} = AdvisoryLocks.try_subscription_lock(@locks, 999_999) @@ -966,6 +1023,10 @@ defmodule EventStore.AdvisoryLocksTest do holder end + defp postgrex_config do + Config.parsed(TestEventStore, :eventstore) |> Config.default_postgrex_opts() + end + defp lock_subscriptions_table(%{conn: conn, schema: schema}) do reply_to = self() From 1e0c7877858d2a6249adb4e1cdaa22d5277ac2c9 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sun, 25 Oct 2026 14:43:59 -0400 Subject: [PATCH 2/2] fix(subscriptions): keep a failed repeated claim from giving up a lock the owner still holds Signed-off-by: Yordis Prieto --- lib/event_store/sql/statements.ex | 2 +- .../statements/bump_lock_generation.sql.eex | 4 ++ .../claim_subscription_lock.sql.eex | 16 ------ lib/event_store/storage/lock.ex | 56 +++++++++---------- test/storage/subscription_lock_test.exs | 2 +- 5 files changed, 32 insertions(+), 48 deletions(-) create mode 100644 lib/event_store/sql/statements/bump_lock_generation.sql.eex delete mode 100644 lib/event_store/sql/statements/claim_subscription_lock.sql.eex diff --git a/lib/event_store/sql/statements.ex b/lib/event_store/sql/statements.ex index 71457dcc..b165d7fa 100644 --- a/lib/event_store/sql/statements.ex +++ b/lib/event_store/sql/statements.ex @@ -22,7 +22,7 @@ defmodule EventStore.Sql.Statements do {:try_advisory_session_lock, [:schema]}, {:advisory_unlock, [:schema]}, {:bound_lock_wait, []}, - {:claim_subscription_lock, [:schema]}, + {:bump_lock_generation, [:schema]}, {:subscription_ack, [:schema]}, {:insert_snapshot, [:schema]}, {:delete_snapshot, [:schema]}, diff --git a/lib/event_store/sql/statements/bump_lock_generation.sql.eex b/lib/event_store/sql/statements/bump_lock_generation.sql.eex new file mode 100644 index 00000000..b2b2153a --- /dev/null +++ b/lib/event_store/sql/statements/bump_lock_generation.sql.eex @@ -0,0 +1,4 @@ +UPDATE "<%= schema %>".subscriptions +SET lock_generation = lock_generation + 1 +WHERE subscription_id = $1 +RETURNING lock_generation, last_seen; diff --git a/lib/event_store/sql/statements/claim_subscription_lock.sql.eex b/lib/event_store/sql/statements/claim_subscription_lock.sql.eex deleted file mode 100644 index 798fbaea..00000000 --- a/lib/event_store/sql/statements/claim_subscription_lock.sql.eex +++ /dev/null @@ -1,16 +0,0 @@ -WITH lock AS ( - SELECT pg_try_advisory_lock( - '"<%= schema %>".subscriptions'::regclass::oid::int, - (CASE WHEN $1 > 2147483647 THEN mod($1, 2147483647) ELSE $1 END)::int - ) AS acquired, pg_backend_pid() AS pid, COALESCE( - NULLIF(current_setting('eventstore.session_id', true), ''), - set_config('eventstore.session_id', md5(random()::text || clock_timestamp()::text), false) - ) AS session_id -), lease AS ( - UPDATE "<%= schema %>".subscriptions - SET lock_generation = lock_generation + 1 - WHERE subscription_id = $1 AND (SELECT acquired FROM lock) - RETURNING lock_generation, last_seen -) -SELECT lock.acquired, lock.pid, lock.session_id, lease.lock_generation, lease.last_seen -FROM lock LEFT JOIN lease ON true; diff --git a/lib/event_store/storage/lock.ex b/lib/event_store/storage/lock.ex index 2e8ec06a..ff99833e 100644 --- a/lib/event_store/storage/lock.ex +++ b/lib/event_store/storage/lock.ex @@ -55,41 +55,22 @@ defmodule EventStore.Storage.Lock do @doc """ Takes the advisory lock of a subscription and bumps its `lock_generation` in - the same statement, returning the lease that fences the subscription's + the same transaction, returning the lease that fences the subscription's progress writes to this lock owner. """ def claim_subscription_lock(conn, subscription_id, opts) do {schema, opts} = Keyword.pop(opts, :schema) - query = Statements.claim_subscription_lock(schema) - - reply = - with_bounded_lock_wait(conn, opts, fn conn -> - Postgrex.query(conn, query, [subscription_id], opts) - end) - - case reply do - {:ok, %Postgrex.Result{rows: [[false, _backend_pid, _session_id, _generation, _last_seen]]}} -> - {:error, :lock_already_taken} - - {:ok, %Postgrex.Result{rows: [[true, _backend_pid, _session_id, nil, nil]]}} -> - with :ok <- unlock(conn, subscription_id, [schema: schema] ++ opts) do - {:error, :subscription_not_found} - end - - {:ok, %Postgrex.Result{rows: [[true, backend_pid, session_id, generation, last_seen]]}} -> - token = FencingToken.new(subscription_id, generation) - - {:ok, Lease.new(token, last_seen, Session.new(backend_pid, session_id))} - - {:error, %Postgrex.Error{} = error} -> - _ = unlock(conn, subscription_id, [schema: schema] ++ opts) - - {:error, error} - - {:error, %DBConnection.ConnectionError{}} = reply -> - reply - end + # Every wait happens before the advisory lock is tried, so a failed claim + # never has to give back a lock that may be a hold its owner already had. + with_bounded_lock_wait(conn, opts, fn conn -> + with {:ok, %FencingToken{} = token, last_seen} <- + bump_lock_generation(conn, subscription_id, schema, opts), + {:ok, %Session{} = session} <- + try_acquire_exclusive_session_lock(conn, subscription_id, [schema: schema] ++ opts) do + {:ok, Lease.new(token, last_seen, session)} + end + end) end def unlock(conn, key, opts) do @@ -104,6 +85,21 @@ defmodule EventStore.Storage.Lock do end end + defp bump_lock_generation(conn, subscription_id, schema, opts) do + query = Statements.bump_lock_generation(schema) + + case Postgrex.query(conn, query, [subscription_id], opts) do + {:ok, %Postgrex.Result{rows: [[generation, last_seen]]}} -> + {:ok, FencingToken.new(subscription_id, generation), last_seen} + + {:ok, %Postgrex.Result{rows: []}} -> + {:error, :subscription_not_found} + + {:error, _error} = reply -> + reply + end + end + # A query that outlives its timeout drops the connection along with every lock # the session holds, so waiting on a lock held on the subscriptions table gives # up well before that. diff --git a/test/storage/subscription_lock_test.exs b/test/storage/subscription_lock_test.exs index 36c78d74..e1aa2ab3 100644 --- a/test/storage/subscription_lock_test.exs +++ b/test/storage/subscription_lock_test.exs @@ -90,7 +90,7 @@ defmodule EventStore.Storage.SubscriptionLockTest do ProcessHelper.shutdown(other) end - test "a claim that fails after taking the advisory lock leaves the subscription claimable", + test "a claim that cannot lock the subscription row leaves the subscription claimable", context do %{postgrex_config: postgrex_config, conn: conn, schema: schema} = context %{subscription_id: subscription_id} = create_subscription(context)