Skip to content

perf(postgres): enqueue, claim and report outcomes in one round trip - #48

Merged
pdevito3 merged 45 commits into
mainfrom
perf/pg-one-round-trip
Nov 27, 2026
Merged

pdevito3 merged 45 commits into
mainfrom
perf/pg-one-round-trip

Conversation

@pdevito3

@pdevito3 pdevito3 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Cuts Postgres round trips on the hot paths. Part of issue 0296 (BackWave on Postgres against Acta).

Call Before After
Plain enqueue transaction 1 round trip (autocommit)
Warm claim on a Queue seen unlimited and unpaused transaction 1 round trip
Outcome batch with no output, tags, or child edges transaction 1 round trip

The transaction forms stay for the other cases: enqueue with parents or tags, a limited or paused Queue, an outcome batch with output, tags, or a terminal job with child edges. The round-trip budget tests now count commands and commits.

Correctness of the one-statement claim

The claim reads candidates from its snapshot and locks them with FOR UPDATE SKIP LOCKED. If a job row changed after the snapshot (another writer appended to its Transition Log), the claim skips that row with a per-row filter on the locked row version (xmin), and claims the rest of the take in a transaction. This keeps Transition Log ordinals in order and within MaxTransitionsPerJob. No schema change. The per-row filter has no measurable throughput cost.

The lease-fencing TLA+ model now covers the Transition Log (invariants LogOrdered, LogCapped, NoOrdinalCollision) and has three new mutants that fail as expected. check.sh --all passes. The commit-horizon model citations are updated, and both model skills now define the sync commit as the last commit that changed the spec.

Release notes

  • Fix: MaxTransitionsPerJob below 1 is now rejected with ArgumentOutOfRangeException at startup, on every adapter. The setting is a cap, and a cap below 1 was never valid. On main, 0 happened to keep no history on some paths. To record no history, set HistoryPolicy to JobHistoryPolicy.Off, as the error message says.
  • Not breaking: a plain Postgres enqueue inside an ambient TransactionScope still throws InvalidOperationException, as on main (Npgsql: "A transaction is already in progress"). The message now names the fix: pass the NpgsqlTransaction to EnqueueAsync. Without this check, the new autocommit enqueue would succeed outside the scope.

Max Auto Prepare stays opt-in

BackWave does not turn it on. Users can add Max Auto Prepare=64 to the connection string for more throughput. Do not set it behind PgBouncer in transaction mode unless PgBouncer is 1.21 or later with max_prepared_statements above 0. The README says so.

Known cost

An idle poll on a warm Queue now fires the observer_log_register statement trigger, because the claim's transition insert runs with 0 rows. Measured: server CPU per empty claim 133 µs at base, 181 µs at the tip, about 1.5% of one core for 8 Pumps polling every 25 ms. Client latency per idle poll drops from 1.06 ms to 0.59 ms. No Commit Horizon delay was measurable under load. The cost is noted at the claim.

Measured (local mode, M1 Max, indicative)

This PR combined with the UnwrittenOutcomeSlots PR, all opt-ins on (B = 40, Max Auto Prepare=64, benchmark claim bound 128), against main, median of 3 rounds: drain-noop 2.01x, drain-10ms 1.34x, max-sustained 1.65x.

Review

Three review rounds (bugs and code quality). Round 3 had no M findings. Follow-up: backwave-admin issue 0310.

Tests

Release build 0 warnings. Postgres.Tests 322/322 (Category!=Soak).

Checklist

  • I was invited to submit this contribution.
  • I have signed the Contributor License Agreement.
  • The change is surgical - it touches only what's necessary.
  • Public members of shipped assemblies have complete XML documentation.
  • I added or updated tests, and dotnet test passes.
  • dotnet build is warning-free.

The counter saw statements only, so a change that folds a COMMIT into an
autocommit statement could not move a budget. COMMIT now goes through a
counted wrapper that the seam test enforces, every budget pins its commits
beside its statements, and a new budget pins the warm claim a running Pump
makes (2 statements + 1 commit), which the cold-claim budget never reached.
A running Pump's claim sent the lease UPDATE, the Leased transition insert
and a COMMIT: 3 round trips. On a queue the store has seen unlimited and
unpaused in the last 5 s it is now one autocommit statement whose CTEs write
the lease, the transitions and the capped prune together.

The statement reads every ordinal from the snapshot it started with. If a
transition for a job it locks committed after that snapshot (another claimer
leased the job and handed it back in that window), the insert collides on
the primary key and the statement rolls back whole; the claim then reruns
as the two-statement transaction, whose insert reads a snapshot taken after
the row locks. A test forces that collision.

The cold path (config lock and read) is unchanged, so the first-config
interleaving clauses still park inside it.
A plain outcome batch sent the fenced UPDATE, the transition insert, the
child-latch probe and a COMMIT: 4 round trips. It is now one command of two
statements, which Npgsql runs as one implicit transaction. The first locks
the fenced rows in id order. The second, in a snapshot taken after those
locks, checks whether any row it makes terminal parents a Dependency and,
when none does, writes the outcomes, transitions and capped prune as CTEs.

The probe cannot be skipped: a child can be enqueued while its parent is
leased, so only the store knows. Reading it after the locks matters: a
child enqueue that holds the parent's lock commits its edge before our
snapshot, and a test parks one there to prove the child is released.

A batch whose rows parent a Dependency, or carry output or added tags, runs
the existing transaction, which cascades the latch with the terminal write.
An EnqueueAsync outside a caller transaction opened its own transaction for
the job insert, then committed: 2 round trips. A job with no parents and no
tags is one statement, the job row and its first transition in one CTE, and
its first ordinal is below any cap, so nothing prunes. It now runs as
autocommit: 1 round trip.

Transactional Enqueue, parented and tagged jobs keep the transaction. The
post-commit Wake-Up Hint still goes only after the statement returns, and
the enqueue failpoint fires before the lone statement, where a crash leaves
nothing, as the rollback did.
…ements

The store leaves Max Auto Prepare to the connection string. Npgsql already
reads it there, so the option docs and the package README name it as the
opt-in for direct connections, and warn against it behind PgBouncer in
transaction mode.
…hat cascades

The one-round-trip outcome write fired the report-outcome failpoint before
it sent anything, so the batched crash-before-cascade conformance test threw
before any write and passed without reaching the real point, and a gated
batch fired the name twice. The write is one atomic command with no seam, so
it now reaches no failpoint. A gated batch reaches the one between the
terminal write and the latch cascade.
A job always keeps the transition it just recorded, and the Postgres
statement that appends and prunes in one pass cannot drop the row it
inserts, so a cap of 0 kept one row there and none on the other stores.
StoreBounds now rejects a cap below 1. The Postgres prune test that pinned
cap 0 now covers cap 1 only.
The one-statement enqueue ran as autocommit on a connection that had
enlisted in the ambient scope, so it returned Ok and sent the Wake-Up Hint
before the scope committed, and a scope rollback erased the job. Inside a
scope the enqueue now takes the transaction path, which throws as it did
before the one-statement enqueue.
PgBouncer 1.21 added prepared statements in transaction mode, but
max_prepared_statements stayed 0 by default until 1.24. The option docs and
the README now say to set Max Auto Prepare behind PgBouncer only from 1.21
with max_prepared_statements above 0, say what 64 counts, and put the README
note with the connection string, since it is not a PostgresStoreOptions
property.
…ne statement

The adapter had four transition-log writers with two prune formulas: the
claim and outcome CTEs, the batch recorder's INSERT then correlated DELETE,
the per-row recorder and its prune, and the enqueue's inline ordinal-0
insert that pruned on one path only. TransitionLogCtes is now the only
transition SQL. The batch recorder runs it over an unnest source in one
statement, the per-row recorder is a batch of one, and the enqueue runs it
over the rows its insert returns. A write that takes a job past the cap no
longer pays a second statement for the prune.
The one-round-trip write and the transaction's inline UPDATE duplicated the
SET list and the fence, and the unnest column list existed three times. Both
paths now run the same lock, write and transition command; the transaction
runs it without the child-edge gate, then writes output and tags and runs
the latch cascade. The command returns the gate as an explicit column
instead of a sentinel row, and both paths return the set of applied ids.
OutcomeVector.From builds the vector, transition details included, once.
EnqueueCoreAsync took a nullable transaction as a mode flag and branched on
it three times. The core now always runs on a transaction, the one-statement
enqueue is its own small method, and both build the insert through
InsertJobAsync.
The claim and the outcome dispatch each tried the fast path behind a
condition and then filled a null with the slow path, and the claim's
transaction re-read the time-based unlimited-Queue cache. Each now decides
once, and the claim passes the decision into its transaction.
The claim and the enqueue fired their failpoint names before a one-statement
write as well as between the effects of a transaction, so one name covered
two store states. A one-statement write has no point between effects, so it
now reaches no failpoint, and the FaultHook contract says so. Torture and
VOPR do not arm failpoints by name. The telemetry fault tests enqueue a
tagged job, which still reaches the enqueue failpoint.
Drop the em dashes and the ADR references from the moved comments, move the
Job Tags note out of the claim's SQL text, and replace the stale note that a
cached Queue pays nothing with what readConfig decides.
The round-trip counter and the budgets now name what they count, commands,
since one command can hold two statements. The prune test drops its
round-trip half, which only repeated the budget test, and keeps the history
count. The ordinal-collision test drops its count pin and says what the
forged row stands in for. Both race tests share one lock-wait helper that
waits on the store under test by its application name, not on any lock
wait in the database.
…nsert

The shared append-and-prune CTEs made the enqueue statement read MAX(ordinal),
sort, and prune for a job that has no transitions yet. Without prepared
statements Postgres planned that larger statement on every enqueue: the
single-producer enqueue p50 rose from about 0.62 to 0.98 ms, and the
max-sustained arrival rate fell from about 8,600 to 5,900 jobs/s (local mode,
M1 Max, indicative). A new job's first transition is ordinal 0, below any cap
of 1 or more, so the enqueue inserts it directly again.
…se fencing

The Postgres batch outcome is now one command of two statements: a
waiting FOR NO KEY UPDATE of the fenced rows, then the fenced UPDATE on a
snapshot taken after the locks. The model still treated it as one UPDATE
step. Postgres now takes ReportLock and ReportCommit like the other
adapters, with a row that fails the lock fence left unlocked and fenced
again at the write.

The claim keeps its row lock shape in both forms. The one-statement form
rolls back whole on a transition ordinal collision, which the model
reaches as a rollback. Move the sync commit to 085700e and update the
Postgres line citations and the coverage record.

check.sh --all matches on every config. With the fence dropped from the
Postgres outcome write, postgres.cfg ends on OutcomeFenced.
A batch that carries one job twice applies one of its outcomes. The latch
cascade read the terminal state from the request, so a retry that won the
UPDATE could still release the children of a parent left Scheduled. The
outcome command now returns the state it wrote, and the cascade reads it.
The fallback after an ordinal collision skipped the queue_limits read on
the strength of the cached unlimited stamp, so a Pause set between the two
attempts was not seen. With the readConfig flag gone there is one
transaction claim path, and it always reads the config.
…n CTEs

TransitionLogCtes returns nothing under Off and otherwise leads with its
comma, so the claim and the outcome command each have one shape. The
ungated outcome command names its gate NoGate.
…up front

The store now throws its own InvalidOperationException before it opens a
connection, instead of routing the enqueue to the transaction path and
letting BeginTransaction fail. The routing no longer checks the scope.
…ged after its snapshot

The one-statement claim read the Transition Log ordinal and pruned from its
statement snapshot, which can be older than the row it locks. A job leased
and handed back in that window got an ordinal below the newest one, and the
prune missed rows committed after the snapshot, so the job kept more rows
than MaxTransitionsPerJob. The claim now compares the job row version (xmin)
its snapshot sees with the version it locked, writes nothing when any
differs, and the caller claims in a transaction. The primary-key collision
fallback is gone, so a collision now surfaces as an error.
…se fencing writers

The lease fencing model now carries each job's Transition Log: every
writer appends MAX + 1 and prunes to the cap, and the Postgres
one-statement claim reads both from its snapshot behind the row-version
gate. New rules LogOrdered, LogCapped and NoOrdinalCollision hold on all
three adapters at a cap of 1. The mutants ordinal-from-snapshot,
no-window-check and legacy-writer-no-bridge each break a rule. Citations
move to the fix commit.
…row version

The window check added a gate CTE that read every candidate row again from
the snapshot, plus an admitted CTE and a final join. That made the claim cost
about 0.1 ms more per call to plan and run, and max-sustained throughput
dropped about 8 percent.

The claim UPDATE now writes only a row whose snapshot version has the xmin
that FOR UPDATE locked. Its scan reads the snapshot version, so a row that
changed after the snapshot fails the filter before any write, and no
EvalPlanQual re-check can replace it with the newer version. The statement
returns the candidate count. When it skipped a candidate, the caller claims
the rest of the take in a transaction. A CASE wraps the filter so that the
planner does not estimate one row for the Transition Log CTEs.

The lease fencing model now skips the changed rows instead of standing the
whole statement down, and its citations follow the new line numbers.
…im filter

The sync commit is now the last commit that changed LeaseFencing.tla, so
it moves with the model and needs no hash. Record the postgres.cfg
distinct-state count and the check.sh --all run time after the Postgres
two-statement outcome, the Transition Log, and the per-row claim filter
joined the model. The Oracle and SQL Server counts do not change.
…contradicts

FillTransitionsUpToAsync(churner, cap - 1) already leaves cap rows, so the claim, not the report, made the first prune, and the bystander was never asserted. The batch boundary and the multi-job prune are pinned by the two tests above it.
Assert 5 commands and 1 commit. A claim that went straight to the transaction path counts (4, 1), which the old commit-only assertion could not tell apart.
…tion token

The Lease commits with the statement, so a read cancelled after it ran left the jobs leased to this worker, unseen, until the Lease expired, each with an attempt spent. A token cancelled before the statement is sent still cancels the claim.
… claim

An idle claim runs the 0-row Transition Log insert, so observer_log_register fires and takes the shared epoch lock. Measured at about 50 us more backend CPU per empty claim than the base claim transaction, while the claim saves one round trip.
…stores

Map every citation in both specs and skills from the commit it was written against (ad5b0ab for the short commit horizon forms, c929675 otherwise) with a difflib line mapping, so each cited line holds the same text. By hand: the Observer commits now read CommitCountedAsync, and the transaction claim cites its transition insert instead of its UPDATE.
@pdevito3
pdevito3 merged commit 5a940ca into main Nov 27, 2026
2 checks passed
@pdevito3
pdevito3 deleted the perf/pg-one-round-trip branch November 27, 2026 05:04
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