Skip to content

[connectors] Postgres output: do not block the stop of the pipeline - #8204

Open
bestouff wants to merge 4 commits into
mainfrom
issue-8021
Open

bestouff wants to merge 4 commits into
mainfrom
issue-8021

Conversation

@bestouff

@bestouff bestouff commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

Linked Issue

Fixes #8021. Found during the review of #8017 (related to #8014).

What changes

A pipeline could fail to stop when the Postgres output connector waited for a server or a pooler that accepted the TCP connection and did not answer. The synchronous postgres client cannot end a call from another thread, so the worker can stay in its call. This PR makes sure that nothing on the output thread waits for such a worker when the pipeline stops, as the rule on OutputEndpoint requires.

Wait Before After
Endpoint waits for the reply of a worker (batch_start, encode, batch_end) recv(), no limit Looks at the shutdown token every 100 ms, gives up when the pipeline stops
Endpoint sends a command to a worker (channel of capacity 1) send(), no limit The same as above
Drop of the endpoint Joins each worker, no limit Sends Shutdown without a wait, gives all workers 1 s together, joins the ones that ended, leaves the others with a warning (they end with the process)
A wait that was abandoned - Not reported as a transport or encode error. A later wait checks the token first, so it cannot take a late reply for a new command

An endpoint with no controller (tests, benchmarks) waits as before.

Not changed (out of scope):

  • No time limit for the database calls themselves (connect_timeout, statement timeout).
  • The connect and prepare in PostgresOutputEndpoint::new, which run when the pipeline starts, not on the output thread.

Describe Manual Test Plan

Test Result
New suite case stops_with_an_unanswered_statement: the proxy takes a statement of a transaction and gives no answer; the pipeline is stopped Pass: stops within 20 s
New suite case stops_with_an_unanswered_login: the proxy ends the session, then takes the next login and gives no answer Pass
New unit test drop_returns_with_a_blocked_worker Pass: the drop returns in about 1 s
Revert check: the endpoint ignores the shutdown token Both suite cases fail: the pipeline did not stop within 20 seconds
Revert check of the unit test (reported by the implementation run): the old drop Fails: the endpoint did not drop within 5 seconds
Postgres unit tests and Postgres suite 127 unit tests pass. Suite: 80 pass, 17 ignored, the 2 TLS cases fail (no TLS server locally)
Clippy with warnings as errors, all targets Pass

This PR touches the same functions as #8020, #8027, #8096 and #8098. The ones that merge later need a rebase. #8096 changes the protocol between the endpoint and its workers; after it, the waits of this PR are only in batch_end.

Checklist

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

Breaking Changes?

None.

@bestouff
bestouff marked this pull request as draft December 3, 2026 14:07
@mythical-fred-oss

Copy link
Copy Markdown
Contributor

LGTM. This fixes the hang in #8021: when the pipeline stops, the endpoint no longer waits on a Postgres worker stuck in a call that never returns.

What I ran (debug build, no local Postgres)

Check Result
cargo test -p dbsp_connectors --lib parallel::drop_returns_with_a_blocked_worker pass (~1 s)
batch_start_gives_up_while_the_pipeline_is_stopping could not run: needs a live Postgres (connection refused)
Suite cases stops_with_an_unanswered_{statement,login} not run (no Postgres service here)
Extra QA unit test (below) pass

Gates: tests, docs and changelog are present. The commit message is good. There is no unsafe code and no new dependency. The SQL type coverage rule does not apply because the PR does not change the encoding.

Missing (medium): no unit test, without Postgres, for the shutdown path of broadcast_and_collect/receive_reply. The suite cases do cover it, but they only run when a Postgres service is up. Nothing checks the "a later wait cannot take a late reply" invariant directly. Here is a test I wrote and ran locally (it passes):

+        #[test]
+        fn broadcast_gives_up_on_shutdown_with_a_silent_worker() {
+            use super::super::{BroadcastCommand, WorkerHandle, WorkerResult};
+            use std::time::{Duration, Instant};
+            use tokio_util::sync::CancellationToken;
+            let (release, blocked) = crossbeam::channel::bounded::<()>(0);
+            let (cmd_tx, cmd_rx) = crossbeam::channel::bounded(1);
+            let (result_tx, result_rx) = crossbeam::channel::bounded(1);
+            let thread = std::thread::spawn(move || {
+                let _cmd = cmd_rx.recv();
+                let _ = blocked.recv();
+                let _ = result_tx.send(WorkerResult::Ok { num_bytes: 1, num_rows: 1 });
+            });
+            let token = CancellationToken::new();
+            let mut endpoint = PostgresOutputEndpoint { /* as in drop_returns_with_a_blocked_worker */
+                shutdown_token: Some(token.clone()), /* ... */ };
+            token.cancel(); // (or cancel from another thread after the wait starts)
+            assert!(endpoint.broadcast_and_collect(BroadcastCommand::BatchEnd).is_err());
+            // The late reply must not be taken by the next command.
+            drop(release);
+            assert!(endpoint.broadcast_and_collect(BroadcastCommand::BatchStart).is_err());
+            assert_eq!(endpoint.num_rows, 0);
+        }

Other uncovered cases (low): a Drop while the command channel is still full from an abandoned send_command, where try_send(Shutdown) fails and the worker exits only when its reply send fails. A multi-thread (threads > 1) variant of the stop cases.

@bestouff

bestouff commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. Added a variant of your test in 36cec7f: wait_for_a_silent_worker_ends_on_shutdown. The token is cancelled after the worker took the command, so the cancel lands during the wait. It then checks that the next wait does not take the late reply. Without the shutdown check it fails (the wait does not end). I left the two low cases out.

@blp blp added connectors Issues related to the adapters/connectors crate bug Something isn't working labels Dec 3, 2026
A pipeline could fail to stop when the Postgres output connector waited
for a server or a connection pooler that accepted the TCP connection
and then did not answer. The worker thread stayed in a synchronous call
of the postgres client, which has no way to end the call from another
thread. The endpoint waited for the reply of the worker with no limit,
on the output thread of the controller, which the teardown joins. The
drop of the endpoint also joined each worker with no limit.

The endpoint now keeps the shutdown token of the pipeline. Each send to
a worker and each wait for a reply looks at the token every 100 ms and
gives up when the pipeline stops. A later wait checks the token first,
so it cannot take a late reply for a new command. An abandoned wait is
not reported as an error of the connector.

The drop of the endpoint sends Shutdown without a wait, gives all the
workers one second together to end, joins the ones that ended, and
leaves the others with a warning. Such a thread is in a call to
PostgreSQL, and ends with the process.

Not changed: there is still no time limit for the calls themselves, and
the connect and prepare when the pipeline starts.

Two suite cases use a new proxy fault that takes a statement, or a
login after a lost session, and gives no answer. Each checks that the
pipeline then stops within 20 seconds. A unit test checks that the
drop returns with a worker that does not end. All three fail without
the fix.

Fixes: #8021
Signed-off-by: Xavier Bestel <xavier.bestel@feldera.com>
A unit test with a worker that takes a command and does not answer:
when the pipeline stops during the wait, the wait ends with an error,
and the next wait does not take the late reply of the worker. The test
needs no PostgreSQL server. It fails without the shutdown check.

Signed-off-by: Xavier Bestel <xavier.bestel@feldera.com>
A worker that was left behind in a call to PostgreSQL could go on when
the server answered later, and commit its batch after the stop had
returned. The worker now checks whether its pipeline stopped before
each statement and before COMMIT, and rolls back instead. A COMMIT that
was already sent can still complete. A worker built with no controller,
as in tests, never counts as stopped for this check; one whose
controller is gone does.

The docs and the changelog now say that a graceful stop of a pipeline
with checkpoints first makes a checkpoint, which waits for the output
of the connector, so it can stay in Suspending while the server does
not answer, and that /stop?force=true does not wait.

Tests:
- The unit test of the silent worker cancels only after the endpoint
  has waited in its receive loop, and checks that a cancelled wait
  leaves the late reply in the channel.
- The test proxy no longer lets a server timeout release a held client:
  for a held login it opens no server connection, and for a held
  statement the relay from the server stops while the fault holds the
  session. The two stop cases still fail without the fix.

Signed-off-by: Xavier Bestel <xavier.bestel@feldera.com>
@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
Comment thread docs.feldera.com/docs/changelog.md Outdated
Comment on lines +30 to +41
- Connectors: a pipeline with a PostgreSQL output connector now stops when
the server or a connection pooler does not answer. Before, the stop could
wait with no time limit.

- Connectors: the stop of a pipeline with a PostgreSQL output connector no
longer waits for a server or a connection pooler that does not answer.
Before, the stop could wait with no time limit. A graceful stop of a
pipeline with checkpoints first makes a checkpoint, which waits for the
output of the connector, so it can stay in `Suspending`; use
`/stop?force=true` in that case. A writer thread that sees the stop
before it sends `COMMIT` rolls back its part of 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.

bug (medium): These are two entries for the same fix. The first one, from commit 1, repeats the opening of the second. Keep only the second entry.

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 3a61218: the first entry is removed. It was a duplicate from a rebase.

}

// A stop cannot cancel a COMMIT that the worker has already sent.
if self.controller_requested_shutdown() {

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 test (medium): No test covers the roll-back-instead-of-COMMIT path (or the skip in exec_statement at L300). Both stop cases end the proxy session on release, so the worker never gets as far as COMMIT. Suggested suite case: add a fault that holds a B and then forwards it on release. Then hold, call controller.stop(), release, give the worker time to finish, and assert the target table has none of the batch's rows. Without that test, nothing would notice if the check were removed and a late COMMIT landed after the stop.

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 in 3a61218: rolls_back_a_batch_after_stop. A new proxy fault holds a Bind and forwards it on release. The case stops the pipeline, releases, waits for the session to end, and checks that the table is empty and that the sequence of the table advanced once. Without the check before COMMIT the table has 1 row. Without the skip in exec_statement the sequence is at 2.

@mythical-fred-oss

Copy link
Copy Markdown
Contributor

What I ran

Check Result
cargo test -p dbsp_connectors --lib for drop_returns_with_a_blocked_worker and wait_for_a_silent_worker_ends_on_shutdown pass, 15 out of 15 runs (no flakes)
cargo clippy -p dbsp_connectors --tests and rustfmt --check on the changed files clean
Postgres suite cases (stops_with_an_unanswered_*) not run: no PostgreSQL here

Review

  • The design matches the OutputEndpoint rule that every wait must end on shutdown. The controller already ignores encode errors once the token is cancelled, and batch_end and batch_start now do the same.
  • missing (medium): commit 3 changes behaviour (a worker that sees the stop rolls back instead of committing), and no test covers it. See the inline comment for a suggested case.
  • bug (medium): the changelog has two entries for this one fix (inline).
  • pitfall (low-medium): the PR says an endpoint with no controller "waits as before". That holds for the waits, but Drop now gives up after 1 s even with no controller. A test or benchmark could then leave a worker thread running with an open connection.
  • Gates: no unsafe, no new dependencies, docs updated, no breaking change.

With those two fixed, this looks good to merge.

No test reached the check before COMMIT, or the skip of a statement
after the pipeline stopped: both stop cases ended the proxy session,
so the worker never got that far. The new suite case holds a statement
in the proxy, stops the pipeline, and then lets the statement through.
The table must have no row of the batch, and the sequence of the table
must show that no later statement reached the server. Each of the two
checks, when removed, fails the case.

The drop of the endpoint gave up on its workers after one second also
for an endpoint with no controller, so a test or a benchmark could
leave a worker thread with an open connection. Apply the limit only
when the endpoint has the shutdown token of a pipeline.

Remove a duplicate changelog entry that a rebase left.

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 points, as of 3a61218:

Point Status
No test for the rollback instead of COMMIT Added, see the inline reply
Two changelog entries Fixed, see the inline reply
Drop gives up after 1 s also with no controller Changed: the limit applies only when the endpoint has the shutdown token of a pipeline. With no controller it joins its workers as before. Test: drop_without_a_controller_joins_the_worker

@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.

A question before I review the details: when does this hang happen in production? On stop, the manager kills the pipeline process. A graceful stop with a checkpoint still hangs with this PR, as the new docs say. If the fix is for in-process stops only, please say so in the description.

Also, changelog.md has two entries for this fix. Please keep one.

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 can block the pipeline shutdown when the server or a pooler does not answer

3 participants