Skip to content

[connectors] Retry a Postgres batch when a pooler ends the session - #8017

Merged
bestouff merged 2 commits into
mainfrom
issue-8014
Dec 2, 2026
Merged

bestouff merged 2 commits into
mainfrom
issue-8014

Conversation

@bestouff

@bestouff bestouff commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Linked Issue

Related to #8014. This PR corrects the first problem of the issue: the Postgres output connector drops a batch when PgBouncer reports SQLSTATE 08P01. The second problem (the completion token reports complete for a dropped batch) is the intended behavior of a token: it reports the end of the processing, also when a connector failed. This PR documents it, and the way to find a dropped batch (the status of the connector).

Stack: #8026 (read-only session) on this PR, and #8098 (max_retries, no limit by default) on #8026. #8099 (updates as INSERT ... ON CONFLICT) is on main.

What changes

PgBouncer reports each error of its own as FATAL with SQLSTATE 08P01, and closes the client session. The connector classified these errors as permanent and dropped the batch.

Area Before After
Error class of a statement error Transient only for a closed connection and a short list of SQLSTATEs Transient if the connection is closed, the error has no SQLSTATE, the SQLSTATE is in class 08 or is 57P01, 57P02, 57P03, or the severity is FATAL or PANIC
Transaction that cannot start A permanent error ended the batch. A transient error retried in a loop with no limit, while the other worker threads held their transactions The worker marks the transaction as lost and does not wait. The batch is written when the batch ends, at most 10 times
Reconnect that fails permanently The batch start looped without a wait The write stops at once and reports the error
Worker thread that has no rows of the batch and loses its transaction Waited for a new connection with no limit, or reported a dropped batch Returns at once. It makes one attempt to connect again for the next batch
Pipeline stop while a worker waits to write a batch again Reported as a fatal error of the endpoint Not reported

A statement that the server rejects in a healthy session stays permanent.

One fact about the failure: when the FATAL error and the end of the stream reach the Rust postgres client in the same read, the client reports "connection closed" and not the error, and a closed connection was retried before this PR too. So the batch was lost only when the client read the error first. The test proxy ends the session only after the next request of the client, so the suite cases always see 08P01, and they assert it.

Known and not changed here, because the behavior is in main before this PR:

Describe Manual Test Plan

I ran a pipeline against PgBouncer 1.26.1 (transaction pooling) in front of PostgreSQL 15, stopped PostgreSQL while a batch of 3000 rows was pending, and started it again.

Run Old code This PR
Rows in the table after the outage 0 of 3000, errors pg_batch_start, pg_exec, pg_batch_end with permanent: SqlState(E08P01) 3000 of 3000, no fatal error. First run: one pg_batch_start error with E08P01 ("the batch will be written again") and 3 pg_conn_retry errors while the server was down. Second run, after the review corrections, on the tree of #8026: the start failed with a closed connection, 6 pg_conn_retry errors
4 classifier unit tests 2 fail 4 pass
3 suite cases with a TCP proxy that ends a session as PgBouncer does (FATAL 08P01, at the transaction start and at the second statement of a batch) and as the server does for the idle-in-transaction timeout (FATAL 25P03) All 3 fail and lose their rows All 3 pass (3 of 3 runs)
Suite case: 2 worker threads and 1 row, the pooler ends the session of the thread with no rows and then fails each login Not applicable (the old batch start waits) Passes. Fails without the change for a worker that has no rows
Revert check: severity rule removed from the classifier The 25P03 case fails
Postgres output suite (not TLS, not the CDC input cases), local PostgreSQL 15 not run 27 of 27 pass

The TLS cases of the Postgres suite were not run locally. The change for a pipeline stop has no test of its own.

Not changed: a pipeline that starts while PgBouncer cannot reach its server fails when the connector prepares its statements, because that path is the endpoint construction, not the batch path.

Docs added after the review: a completion token is complete also for a dropped batch, the pool size rule, and the lock timeout.

Checklist

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

Breaking Changes?

None. The connector now writes a batch again in cases where it dropped the batch before.

match error.parsed_severity() {
Some(severity) => matches!(severity, Severity::Fatal | Severity::Panic),
// Only the localizable severity is present: the sender is a server
// older than 9.6, or a pooler, and poolers do not localize.

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.

what is 9.6? the postgres version or pgbouncer? if postgres, do we care about postgres<10?

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.

PostgreSQL 9.6, the version that added the V field (the severity that is not localized). We don't care about servers that old, but the branch is still needed: PgBouncer sends only S, C and M, so each PgBouncer error goes through it. The comment was misleading; it now names PgBouncer first (done in #8026, which touches the same file).

// One attempt to have a connection for the next batch. If it
// fails, the worker connects again when a batch gives it rows.
if let Err(e) = self.retry_connecting() {
tracing::warn!(

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.

Suggested change
tracing::warn!(
warn!(

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.

That one doesn't compile as is: the file has no use tracing::warn, and every log call in it uses the tracing:: path. Kept it consistent with the rest of the file.


- The PostgreSQL output connector now connects again and writes the batch
again when a connection pooler, such as PgBouncer, ends the session with
an error of its own (SQLSTATE `08P01`). Before, it dropped the batch. It

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.

I'm hoping for a mode to retry infinite times?

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.

Yes: #8098 (stacked on #8026) adds max_retries to the Postgres sink, with no limit by default, as for Delta (part of #8039).

| The connection drops, or the server restarts or is not reachable. | Connects again. The wait between attempts grows to a maximum of 60 seconds. Then writes the batch again. |
| A connection pooler, such as PgBouncer, reports an error and ends the session. An example is a pooler that cannot log in to the server. | The same. |
| The same batch fails 10 times because the connection drops or the transaction cannot start. | Reports an error and drops the batch. |
| The server rejects the credentials, or the database does not exist. | Reports an error and drops the batch. |

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.

did we consider this to be fatal/panic?

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.

PostgreSQL sends these as FATAL, but the connect classifier makes them permanent by their SQLSTATE (28P01, 28000, 3D000, 42501), so the FATAL rule doesn't apply. For the pipeline it's a fatal connector error: the batch is dropped, the pipeline goes on, and the next batch tries to connect again. Stopping the pipeline on such an error is the last part of #8039; I'd keep it there.

@bestouff
bestouff added this pull request to stack #8031 November 20, 2026 16:40
@ryzhyk

ryzhyk commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Claude identified three potential issues. I don't think any of them is new in this PR, but they are all related to robust error handling, so worth addressing or tracking as separate issues. I asked claude for fix directions in each case, but I don't know that these are the best solutions possible.

A. Fewer pooled server connections than writer threads (measured).
- PostgresOutputEndpoint::batch_start waits for every worker's START TRANSACTION.
- Behind a transaction-mode pooler, each open transaction holds a server connection. The workers that got one sit idle in their transactions; the others wait in PgBouncer's queue until query_wait_timeout evicts them.

PgBouncer 1.25.2, transaction mode, pool of 2, query_wait_timeout 5 s, one batch of 400 rows:

┌────────────────┬─────────┬────────────┬───────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ Writer threads │ Elapsed │    Rows    │                                                      Errors                                                       │
├────────────────┼─────────┼────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ 2              │ 5.05 s  │ 400 of 400 │ none                                                                                                              │
├────────────────┼─────────┼────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ 4              │ 10.27 s │ 400 of 400 │ one pg_batch_start: two threads saw "connection closed"; the PgBouncer log shows two query_wait_timeout evictions │
└────────────────┴─────────┴────────────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

The test pipeline's own buffering delay accounts for 5 s of each run.
- With #8017 nothing is lost: the evicted workers write their part when the batch ends. On main those rows were dropped.
- The stall is still the full query_wait_timeout, 120 s by default. By the same mechanism it should recur on every batch (inferred; I measured one batch).
- PgBouncer pools are per database and user, so connectors sharing a pool add up. Three 8-thread connectors behind the default 20-connection pool could block each other this way (inferred).
- Fix direction: a worker should never hold a transaction open while waiting for another worker. Each worker could start, write, commit and retry its whole part while handling WorkerCommand::Encode, and batch_end would only collect results. The batch isn't atomic across workers anyway, and workers with no rows would open no transaction at all. At minimum, document that the writer threads of all connectors sharing a pool must not exceed its size.
B. Row locks between workers (inferred, already on main).
- With the default 1 MiB buffer, a large batch writes to the table during encode.
- If the table has a constraint beyond the view's key (a second unique index, a foreign key, a trigger), worker B can block on a row that worker A changed, while A waits at the endpoint for B. Postgres sees no cycle.
- This hangs unless lock_timeout or statement_timeout is set. With either set, #8026's new handling of 55P03 and 57014 breaks the wait.

Fix direction:

Design: the endpoint waits only once per batch, at the end.
- PostgresOutputEndpoint::batch_start and PostgresOutputEndpoint::encode only queue their commands and return.
- PostgresOutputEndpoint::batch_end queues BatchEnd, then collects the replies each worker owes, in order.
- Each worker runs begin, write, commit from its own queue at its own pace. No worker ever waits for another while it holds a transaction.
- A lock wait then ends as soon as the holder commits. A real lock cycle stays inside Postgres, which aborts one side with error 40P01, and #8026 retries it.

Requirements and side effects:
- Each worker's command and result channels must hold a full batch: three commands and three replies. Today they hold one, so a worker would block sending its second reply while holding its transaction, and the barrier would come back.
- The endpoint should count the replies each worker owes, so an error in encode can't shift replies into the next batch.
- Worker errors from Encode get reported from batch_end instead.
- The tests tests::parallel::progress_counter_advances_mid_batch_* assume encode waits for the workers. They would need to wait for the progress counter instead.
- Fast workers commit before slow ones finish, so readers can see a half-written batch for longer. Batches were never atomic across workers anyway.
- The same change removes issue A, because no worker holds a pooled server connection while it waits for another worker.
- #8017's rule that PostgresWorker::start_batch must never wait is no longer needed.
C. A worker that gives up leaves the batch half written, for good.
- In materialized mode an "upsert" is a plain UPDATE (RawQueries::upsert). A later update of a key whose insert was dropped matches no row, so the row stays missing until the key is deleted and inserted again.
- With on_conflict_do_nothing, a dropped delete leaves a stale row that later inserts don't replace.
- This supports making unlimited retries the default for max_retries, as you suggested.

Fix direction:

Make every write say "set key k to row v" or "remove k", never something that depends on the row already being there.

Operation: insert
Today: RawQueries::insert: INSERT … ON CONFLICT (key) DO UPDATE SET every
  column
Idempotent?: yes
Change: none, except with on_conflict_do_nothing
────────────────────────────────────────
Operation: update
Today: RawQueries::upsert: UPDATE … FROM … WHERE key = key, which silently
  skips a missing row
Idempotent?: only if the row exists
Change: write updates as INSERT … ON CONFLICT (key) DO UPDATE. The SET list
  is already identical. Use this form even with on_conflict_do_nothing,
  since the docs say that option doesn't affect updates.
────────────────────────────────────────
Operation: delete
Today: DELETE … USING
Idempotent?: yes
Change: none

What this gets you: re-sending a batch is harmless. Whatever a dropped batch left wrong for a key is repaired the next time that key changes.

Cost: in psql, with 5,000 rows per statement, the median rose from 14.7 ms to 15.3 ms (+4%). One behavior change: BEFORE INSERT row triggers now also fire for updated rows.

Limits:
- A key whose last change was in the dropped batch stays wrong until it changes again. Fixing that needs the dropped part re-sent, for example by the unlimited max_retries you proposed, or a full resync.
- With on_conflict_do_nothing, a dropped delete leaves a stale row, because that option tells inserts not to overwrite it.
- If dropped parts were ever re-sent after later batches, writes would also have to ignore older data. That needs a version column that grows with each batch, DO UPDATE … WHERE t.version < EXCLUDED.version, and deletes stored as versioned tombstones. Otherwise an old insert could bring back a deleted row.

@ryzhyk ryzhyk left a comment

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.

LGTM. @bestouff , it's your call whether to address the issues the SI found here, in another PR, track them as issues, or possibly just document them (e.g., issue B could be addressed by adding it as a caveat in the docs).

@bestouff

Copy link
Copy Markdown
Contributor Author

Thanks! My call:

Also rebased on main (changelog conflict only).

PgBouncer reports each error of its own as FATAL with SQLSTATE 08P01,
and closes the client session. The Postgres output connector classified
these errors as permanent. It dropped the batch when the pooler could
not log in to the server, and when the server connection died under a
transaction.

Classify a statement error by the state of the session. The error is
transient if the connection is closed, if the error has no SQLSTATE, if
the SQLSTATE is in class 08 or is 57P01, 57P02 or 57P03, or if the
severity is FATAL or PANIC. A statement that the server rejects in a
healthy session stays permanent.

A transaction that cannot start no longer ends the batch. The worker
marks the transaction as lost, skips the encode, and writes the batch
when the batch ends, with at most 10 attempts. The batch start does not
wait and does not connect again: the endpoint waits for each worker
before it gives rows to any of them, so a wait there holds the
transactions of the other workers, and it had no limit. The reconnect
loop now reports whether it has a connection. A permanent reconnect
failure stops the write at once, where the batch start looped without a
wait.

A worker that has no rows of a batch does not write the batch again
when its transaction is lost. Before, it waited for a new connection
with no limit, or it reported a dropped batch, although the other
workers had committed all the rows.

A stop of the pipeline that ends the wait of a worker is no longer
reported as a fatal error of the endpoint.

Unit tests cover the classifier. Four suite cases put a TCP proxy
between the connector and Postgres. The proxy answers a chosen message
as PgBouncer does: FATAL 08P01, then it closes the session. It can
also end a session as the server does for the idle-in-transaction
timeout (FATAL 25P03), and it can end the session of one worker only.
Each case checks that the connector saw the SQLSTATE. Without the
fix, the classifier tests fail and three of the suite cases lose all
their rows. The fourth case fails without the change for a worker
that has no rows.

Document how the connector handles a lost connection, and add the
fix to the changelog. The docs also say that a completion token
completes when a connector drops a batch, and that the threads of the
connector hold their transactions while they wait for each other: a
pool with fewer server connections than threads stalls each batch,
and a row lock between two threads needs a lock or statement timeout.

Related: #8014
Signed-off-by: Xavier Bestel <xavier.bestel@feldera.com>
After a failover, a connection pooler can hold a session on the old
primary, which is then a read-only replica. The server rejects each
write with SQLSTATE 25006 and the session stays open. The Postgres
output connector classified this error as permanent and dropped the
batch, and it dropped each later batch for as long as the session
stayed open.

These changes correct this:

- The classifier also treats these errors as temporary: 25006, 55P03
  (lock not available), and the SQLSTATE classes 40 (serialization
  failure, deadlock), 53 (insufficient resources), 57 (operator
  intervention, which now includes a cancelled query), 58 (system
  error) and XX (internal error). The statement and its rows usually do
  not cause them. Where they do, the limit of 10 attempts bounds the
  cost.
- Each new attempt to write a batch opens a new connection. Before, the
  worker kept a session that passed a validity check, and a read-only
  session passes it. The worker closes the old session before the new
  login, because the old session can hold the only connection slot of
  the role. It keeps the new client only together with its prepared
  statements.
- The worker waits between the attempts: the second attempt starts at
  once, and each later attempt waits one second longer, 36 seconds in
  total for the 10 attempts. Before, the attempts on an open session ran
  with no wait.
- A server that answers and does not prepare the statements after a new
  connection uses one of the 10 attempts. The wait with no limit stays
  for a server or a pooler that is not available: a failed login, and
  a connection error (class 08) of any severity, which ends the session
  also when a pooler sends it as ERROR (PgBouncer before 1.16).
- The error for a batch that the worker gives up on states why the
  transaction was lost.

The test proxy can now answer a statement as a server does that cannot
run it, with the session left open. Four new suite cases use it. Each
fails if the change that it covers is removed: the classifier, the new
connection, the order of logout and login (with a role that has one
connection slot), the wait, and the attempt limit for a failed
prepare. Two more cases check that a failed login with severity ERROR
and a pooler that sends ERROR 08P01 at the prepare do not use the
attempts. A unit test covers the wait before each attempt.

Document the new cases, and add the fix to the changelog.

Related: #8014
Signed-off-by: Xavier Bestel <xavier.bestel@feldera.com>
@bestouff
bestouff added this pull request to the merge queue Dec 1, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Dec 1, 2026
@mythical-fred-oss

Copy link
Copy Markdown
Contributor

Verdict: not this PR's fault (high confidence) — flaky pre-existing test on main.

The PR only touches crates/connectors/src/integrated/postgres/*. The only real failure in this run is unrelated:

Job Unit Tests / Rust Unit Tests (gke-runners-arm64)
Test storage::page_cache::tests::drops_page_cache
Panic crates/dbsp/src/storage/page_cache.rs:435 — assertion left == right failed, left: 193, right: 0

The test asserts the OS page cache is fully evicted (0 pages) after drop_page_cache; 193 pages stayed resident. It depends on real kernel page-cache behavior (added 2026-11-09 in aacdf91), which is environment-sensitive and a plausible source of flake on shared runners.

Tracked as #8158, assigned to the test's author. Re-queueing should pass.

@bestouff
bestouff added this pull request to the merge queue Dec 1, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Dec 2, 2026
@bestouff
bestouff added this pull request to the merge queue Dec 2, 2026
Merged via the queue into main with commit 24978cc Dec 2, 2026
1 check passed
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.

3 participants