Skip to content

Spec reproducing the multi-row reserve lock on PostgreSQL (#143) - #265

Draft
dg-novicap wants to merge 1 commit into
collectiveidea:masterfrom
dg-novicap:postgres-reserve-locks-multiple-rows-spec
Draft

dg-novicap wants to merge 1 commit into
collectiveidea:masterfrom
dg-novicap:postgres-reserve-locks-multiple-rows-spec

Conversation

@dg-novicap

Copy link
Copy Markdown

Reproduction for #143 (also collectiveidea/delayed_job#915), the problem PR #177 addresses.

Problem

reserve_with_scope_using_optimized_postgres runs:

UPDATE delayed_jobs SET locked_at = ?, locked_by = ?
WHERE id IN (SELECT id FROM delayed_jobs WHERE <ready> ORDER BY priority, run_at LIMIT 1 FOR UPDATE SKIP LOCKED)
RETURNING *

When the planner executes the sub-select as the inner side of a Nested Loop Semi Join, it re-executes the sub-select for every candidate row of the outer scan. FOR UPDATE reads the latest row versions, and each re-execution skips the rows this same UPDATE already changed (their locked_at is no longer NULL), so the LIMIT 1 moves to the next ready row every time. One reserve then locks the whole ready batch under one worker name, and find_by_sql(...).first silently discards the rest. Postgres considers this query shape unspecified rather than a bug (pgsql-bugs #15715, Tom Lane's reply).

Which plan the planner picks depends on table statistics, so it is intermittent in practice. A high-churn delayed_jobs table with stale reltuples is enough. We hit it in production on PostgreSQL 14 with delayed_job_active_record 4.1.11: one reserve locked nine ready jobs at once, visible in the identical locked_at and locked_by on all nine rows.

The test

spec/delayed/backend/postgresql_reserve_spec.rb makes the plan deterministic by disabling every other join strategy for the example's transaction:

SET LOCAL enable_hashjoin = off; SET LOCAL enable_mergejoin = off; SET LOCAL enable_material = off;
SET LOCAL enable_hashagg = off; SET LOCAL enable_sort = off
  • The first example asserts that EXPLAIN of the reserve statement contains Nested Loop Semi Join under those settings, so the reproduction cannot pass vacuously if a future planner stops choosing that plan.
  • The second example creates five ready jobs, calls Delayed::Job.reserve(worker) once, and expects one row with locked_by = worker.name.

On current master, against PostgreSQL 14.20:

1) Delayed::Backend::ActiveRecord::Job.reserve on PostgreSQL locks exactly one job per reserve
   Failure/Error: expect(described_class.where(locked_by: worker.name).count).to eq(1)
     expected: 1
          got: 5

The spec skips on every other adapter. It is expected to fail on the PostgreSQL CI jobs until the fix below is applied.

Fix (tested, not included in this PR so the failing test stays visible)

A scalar sub-select is planned as an InitPlan and evaluated exactly once. If it ever returned more than one row, Postgres raises more than one row returned by a subquery used as an expression instead of taking silent extra locks. SKIP LOCKED is unchanged.

--- a/lib/delayed/backend/active_record.rb
+++ b/lib/delayed/backend/active_record.rb
@@ -145,7 +145,7 @@ module Delayed
           quoted_name = connection.quote_table_name(table_name)
           find_by_sql(
             [
-              "UPDATE #{quoted_name} SET locked_at = ?, locked_by = ? WHERE id IN (#{subquery}) RETURNING *",
+              "UPDATE #{quoted_name} SET locked_at = ?, locked_by = ? WHERE id = (#{subquery}) RETURNING *",
               now,
               worker.name
             ]

With that one-token change applied locally:

  • the new spec passes (2 examples, 0 failures), and EXPLAIN shows InitPlan 1 with Filter: (id = $2) on the outer scan;
  • the full suite passes on PostgreSQL (105 examples, 0 failures; ActiveRecord 8.1, delayed_job 4.1.13, pg 1.x, PostgreSQL 14.20).

PR #177 reaches the same single-evaluation guarantee with a CTE. On PostgreSQL 12 and later a CTE needs AS MATERIALIZED to keep that guarantee; the scalar sub-select needs no version-specific syntax. Happy to push the fix as a second commit on this PR if you prefer it bundled.

🤖 Generated with Claude Code

…ectiveidea#143)

The optimized PostgreSQL reserve wraps the LIMIT 1 sub-select in
`WHERE id IN (...)`. When the planner picks a Nested Loop Semi Join with
the sub-select on the inner side, it re-executes the sub-select per
candidate row and each execution skips the rows the UPDATE already
changed, so one reserve locks the whole ready batch under one worker.

The spec disables the other join strategies with SET LOCAL so the
rescanning plan is chosen deterministically, asserts that plan through
EXPLAIN, and then expects a single locked row after one reserve.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@dg-novicap
dg-novicap marked this pull request as draft November 5, 2026 17:03
described_class.transaction do
described_class.connection.execute(
%w[enable_hashjoin enable_mergejoin enable_material enable_hashagg enable_sort]
.map { |setting| "SET LOCAL #{setting} = off" }.join("; ")

@dg-novicap dg-novicap Nov 5, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

key idea: to disable all other strategies, and to only allow Nested Loop Semi Join, so that the query always locks more than 1 row

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant