Skip to content

[connectors] Postgres output: workers do not wait for each other in a transaction - #8205

Open
bestouff wants to merge 1 commit into
mainfrom
issue-8096
Open

bestouff wants to merge 1 commit into
mainfrom
issue-8096

Conversation

@bestouff

@bestouff bestouff commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

Linked Issue

Fixes #8096. Found during the work on #8017 and #8026 (related to #8014).

What changes

The endpoint of the Postgres output connector waited for every writer thread three times for each batch (start, encode, end). A thread that finished a round kept its transaction open, with a server connection of the pool and its row locks, until the slowest thread finished the round.

Problem Before After
A Pooler in transaction mode with fewer server connections than writer threads Each batch stopped for query_wait_timeout (120 s by default in PgBouncer), then the threads wrote their part again A thread holds a server connection only from its own BEGIN to its own commit
B Row lock between two threads (trigger, foreign key, second unique index) The batch hung: B waits for the lock of A, A waits at the endpoint for B, PostgreSQL sees no deadlock The thread with the lock commits, the other one goes on

New protocol:

Call Endpoint Worker
batch_start Sets the live count to 0. No command -
encode Splits the batch, reads the extra columns one time, queues Encode for each part, returns Opens its transaction if its part has rows, writes it
batch_end Queues BatchEnd, waits for one reply from each worker Commits (with the existing retries), replies

Other points:

  • The command channel holds the whole batch, so the endpoint never blocks. A worker sends its reply only after it released its transaction.
  • A failed BEGIN and an encode failure are reported by the worker itself (pg_batch_start not fatal, encoder_error), as it already did for its statements, and not when the pipeline is stopping.
  • encode takes the extra column values one time for all workers, so a set_extra_columns after encode returned does not change the batch.
  • A worker with no rows opens no transaction. The special case for an idle worker that lost its session, and its proxy fault, are removed.

Behavior change, in the docs and the changelog: a fast thread commits before a slow one, so a reader can see a part of a batch for longer. A batch was never atomic across threads.

This PR conflicts with #8020, #8021, #8027 and #8098, which change the same file. I will rebase the ones that merge after it.

Describe Manual Test Plan

Test Result
New unit case workers_commit_with_a_shared_row_lock: an AFTER INSERT trigger updates one counter row, 2 threads, one statement per row, 20 rows Pass: all rows and the counter at 20, both threads wrote rows
The same case on main's connector code Fails: the batch did not finish (it waits until the 30 s lock_timeout of the trigger)
New suite case idle_worker_opens_no_transaction: 2 threads, 1 row, through the proxy Pass: one START TRANSACTION
New unit case queued_batch_keeps_extra_columns Pass
Existing tests that read the database or the live count after encode Changed to wait for the condition, with a time limit. No assert removed except the one that the new protocol makes untrue (encode returned after the flushes)
Postgres unit tests and Postgres suite 125 unit tests pass. Suite: 81 pass, 17 ignored, the 2 TLS cases fail (no TLS server locally)
postgres_output benchmark Builds
Clippy with warnings as errors, all targets Pass

Checklist

  • Unit tests added/updated
  • Integration tests added/updated
  • Documentation updated
  • Changelog updated

Breaking Changes?

None in the configuration. Behavior change: see above.

@bestouff
bestouff marked this pull request as draft December 3, 2026 14:07
.get(0);
assert!(terminated > 0, "found no backend to terminate");
.unwrap();
assert_eq!(terminated.len(), 1);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

pitfall (medium): possible flakiness. The old check was count > 0. This one needs exactly one matching backend, and the termination of that backend must return true. These tests are serial, but a backend from the previous test's endpoint (or from a dropped pg_client()) can still appear in pg_stat_activity for a short time after its client is dropped, and its last query can name TEST_TABLE too. If that backend is in the list, len() is 2. If it has already exited, pg_terminate_backend returns false for it. It passed 8 of 8 runs for me locally, but it is still a race. Suggest asserting that at least one backend was terminated, e.g. assert!(terminated.iter().any(|r| r.get::<_, bool>(0))), or filtering on application_name / the worker's pid.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 3fc5077: the case now asserts that at least one backend was terminated.

&& let Some(controller) = self.controller.upgrade()
&& !controller.shutdown_token().is_cancelled()
{
controller.encode_error(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

missing (medium): no test covers this new error path. Encode failures used to come back to the controller from Encoder::encode. Now the worker reports them itself, and no test checks the encoder_error tag (grep finds none). Each worker also reports separately and does not say which writer thread failed, while the old message said "N of the connector's writer threads failed". Please add a case where a part fails to serialize or its cursor fails, and assert that (a) the controller gets one encoder_error, and (b) batch_end still returns. In the cursor-failure case, pending is dropped before it is stored, so write_batch returns Ok((0, 0)) for that part. That behaviour should be checked on purpose too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added worker_reports_cursor_error_and_other_worker_commits in 3fc5077: one part's cursor does not open. It checks one encoder_error, no transport error, batch_end returns, and the other part is in the table. The Ok((0, 0)) for that part is intended and has a comment: the encode error is its report. Without the worker's report the case gets 0 encode errors.

fn start_batch(&mut self) -> Option<anyhow::Error> {
let error = self.batch_start_inner().err()?;
/// the start when the batch ends, within its limit of attempts.
fn start_batch(&mut self) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

observation (medium): error volume. pg_batch_start is now reported once per worker per batch instead of once per batch. During a server outage with threads: N, the endpoint error count and logs grow N times faster than before. Is that intended? If not, consider rate-limiting the report or tagging it with worker-thread-{idx} so the repeats can be told apart.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not intended to grow silently: the message now names worker-thread-N (3fc5077), so the repeats can be told apart. I did not rate-limit it: pg_conn_retry is already reported for each worker in the same way.

@mythical-fred-oss

Copy link
Copy Markdown
Contributor

What I ran

Check Result
cargo check --locked -p dbsp_connectors --tests ✅
cargo test -p dbsp_connectors --lib integrated::postgres (local PG 16) ✅
connector_suites -- integrated::postgres::output ×8 ✅ 24/24 every run, including workers_commit_with_a_shared_row_lock and queued_batch_keeps_extra_columns
connector_suites -- integrated::postgres::test ✅ 35 pass, including idle_worker_opens_no_transaction and the pooler fault cases. The 19 failures are CDC/TLS cases that need wal_level=logical or a TLS server, which my environment does not have; none are from this PR

I checked that the controller calls encode exactly once between batch_start and batch_end (push_batch_to_encoder). So bounded(3) is enough, and encode cannot overwrite a batch that is still pending.

Test cases not covered

  • missing (medium): problem A from the description, a pool smaller than threads, has no test. FaultyPooler cannot limit server connections, so the main fix is covered only for the row-lock case (B).
  • missing (medium): encode or cursor failures inside a worker, which are now reported asynchronously (see inline).

Gates: one flakiness risk in batch_start_gives_up_while_the_pipeline_is_stopping (inline; zero-tolerance rule). Fix it or explain why it cannot race. The behaviour change is in the docs and the changelog. The SQL-type-coverage gate does not apply because encoding is unchanged.

@bestouff

bestouff commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. All points are addressed in 3fc5077 (see the inline replies). For problem A: the test proxy can now model a pool of one server connection in transaction mode (a START TRANSACTION waits until the other session's transaction ends). New case two_workers_share_one_server_connection, 2 threads, passes; with main's output.rs it runs into its 30 s limit. Postgres suite: 83 pass, the 2 TLS cases fail as before (no TLS server locally).

@blp blp added connectors Issues related to the adapters/connectors crate bug Something isn't working labels Dec 3, 2026
@bestouff
bestouff marked this pull request as ready for review December 4, 2026 16:50
@bestouff bestouff assigned swanandx and unassigned swanandx Dec 4, 2026
@bestouff
bestouff requested a review from swanandx December 4, 2026 16:55

@swanandx swanandx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM. I ran the Postgres suite and the Postgres unit tests, and they pass. I also ran workers_commit_with_a_shared_row_lock on the connector code of main, and it hangs as you describe.

Please merge this one before #8200 and #8204, because both change code that this PR removes.

@mythical-fred-oss

Copy link
Copy Markdown
Contributor

What I ran (debug, local PostgreSQL 16)

Command Result
cargo test -p static-connectors --test connector_suites -- integrated::postgres::output 26/26 pass
... -- integrated::postgres::test 36 pass, 19 fail, 17 ignored. All 19 failures are CDC cases (no wal_level=logical here) and TLS cases (no TLS server). Every pooler, reconnect, idle-worker and one-server-connection case passes
The 8 new or changed cases (workers_commit_with_a_shared_row_lock, two_workers_share_one_server_connection, idle_worker_opens_no_transaction, worker_reports_cursor_error_and_other_worker_commits, queued_batch_keeps_extra_columns, batch_start_gives_up_…, progress_counter_advances_mid_batch_*), 10 runs in a row 10/10 pass, no flakes
cargo fmt --check -p dbsp_connectors clean

I reviewed the new protocol for hangs. encode is called once for each batch, and the channel holds 3 commands, which covers Encode, BatchEnd and Shutdown, so the endpoint never blocks on a send. BatchEnd is queued as soon as encode returns, so a worker that holds a lock always gets to commit. Workers that get no range return (0, 0) and open no transaction. I found no correctness problem. The tests cover the new behaviour and the error paths (failed start, cursor failure, disconnected worker). Docs and changelog are updated.

  • Gate: commit quality (medium). Please squash answer the review of the new protocol and answer the second review of the new protocol into the main commit before merge. Main has a linear history, and these review-response commits should not land on it.

Otherwise LGTM.

… transaction

The endpoint of the Postgres output connector ran each batch in three
rounds (start, encode, end) and waited for every worker at the end of
each round. A worker that finished a round kept its transaction open,
and with it a server connection of a pool and its row locks, until
the slowest worker finished the round. This caused two problems:

- Behind a pooler in transaction mode with a pool smaller than the
  number of writer threads, each batch stopped until the pooler timed
  out the threads that waited for a connection.
- When a trigger, a foreign key or a second unique index made two
  workers lock the same row, the second worker waited for the lock of
  the first, and the first waited at the endpoint for the second.
  PostgreSQL does not see this as a deadlock, so the batch hung.

The endpoint now waits only once for each batch, at its end:

- batch_start and encode only queue commands and return. encode reads
  the extra column values one time and gives them to all workers, so
  that a later set_extra_columns does not change a batch that encode
  already took. encode sends the part of each worker, also after a
  worker that has ended, and then returns one error that names the
  workers that ended.
- A worker opens its transaction when it gets a part with rows, and
  writes it. A worker with no rows opens no transaction.
- batch_end sends BatchEnd and collects one reply from each worker.
- A worker reports a failed start (pg_batch_start, not fatal, with its
  number) and an encode failure (with its number and the full chain of
  causes) itself, as it already did for its statements.

A fast worker now commits before a slow one, so a reader can see a
part of a batch for longer. A batch was never atomic across workers.

Tests that read the database or the live count after encode now wait
for the condition. The proxy fault for an idle session that is lost
is removed: a worker with no rows no longer opens a session for the
batch. New cases:

- A trigger that updates one row for each insert, two workers and one
  statement per row: hangs on the old code.
- The test proxy as a pool of one server connection, two workers: runs
  into its time limit on the old code.
- A worker with no rows starts no transaction.
- A batch keeps the extra column values of the time when encode took
  it.
- A part whose cursor does not open gives one encoder_error, the batch
  ends, and the other worker commits.
- A worker that has ended does not keep the parts of the other workers
  from being sent.

Docs: the pool and lock notes of the sink page, the extra columns
snapshot, and the PgBouncer setting for named prepared statements.

Fixes: #8096
Signed-off-by: Xavier Bestel <xavier.bestel@feldera.com>
@bestouff

bestouff commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Status of the review point: the two review commits are squashed into the main commit (ec6b6fb). The tree is the same.

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

bug Something isn't working connectors Issues related to the adapters/connectors crate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[connectors] Postgres output threads hold their transactions while they wait for each other

3 participants