Skip to content

Two scans of one attached catalog in a statement run COPY on the transaction's connection at the same time ("lost synchronization with server") #674

Done

Description

@kenstott

Versions

  • DuckDB v2.0.0 with postgres_scanner c0f5a3c, the commit DuckDB v2.0.0 pins
  • duckdb-postgres main as of 2026-11-27 has the same code path
  • PostgreSQL 16.11

What happens

One statement that scans relations of an attached PostgreSQL database many times fails at random:

Failed to prepare COPY "COPY (SELECT "from_term_id", "to_term_id", "rel_type" FROM "org_default"."_term_edges_ontology" WHERE "rel_type" = 'ANTONYM_OF' COLLATE "C") TO STDOUT (FORMAT "binary");": lost synchronization with server

With SET threads = 1 the same statement succeeds on every run.

Reproduce

On a plain PostgreSQL:

CREATE SCHEMA org_default;
CREATE TABLE org_default.terms (id int PRIMARY KEY, name text);
CREATE TABLE org_default.term_edges (id serial PRIMARY KEY, from_term_id int, to_term_id int, rel_type text);
INSERT INTO org_default.terms SELECT g, 'term ' || g FROM generate_series(1, 6) g;
INSERT INTO org_default.term_edges (from_term_id, to_term_id, rel_type) VALUES
  (1, 2, 'DERIVED_FROM'), (2, 3, 'KIND_OF'), (3, 4, 'PART_OF'), (4, 5, 'PREFERRED_TERM_FOR'), (5, 6, 'RELATED_TO');
CREATE VIEW org_default._terms_ontology AS SELECT * FROM org_default.terms;
CREATE VIEW org_default._term_edges_ontology AS SELECT * FROM org_default.term_edges;

In DuckDB, at the default thread count:

ATTACH 'host=127.0.0.1 port=5432 dbname=postgres user=postgres' AS provisa_admin (TYPE postgres, READ_ONLY);
ATTACH ':memory:' AS onto;
CREATE SCHEMA onto.ontology;
CREATE VIEW onto.ontology._terms AS
  SELECT id, name FROM provisa_admin.org_default._terms_ontology;
CREATE VIEW onto.ontology._term_edges AS
  SELECT id, from_term_id, to_term_id, rel_type FROM provisa_admin.org_default._term_edges_ontology;

Then run the statement in duckdb-postgres-concurrent-copy.sql.gz (183 KB uncompressed). It is a recursive CTE whose anchor is a UNION ALL of 20 three-way joins over the two views, followed by ten EXISTS subqueries per row, about 450 scans of the two views in all. It failed on 3 of 3 runs here. Smaller hand-written statements with the same ingredients (a UNION ALL of joins, NOT EXISTS chains, a recursive CTE, a read-write attach of a table) passed every run, so the race needs many scans whose pipelines DuckDB initializes close together.

Code path

  1. PostgresOptimizer::Optimize (src/storage/postgres_optimizer.cpp) finds more than one scan of the catalog. Each scan with max_threads == 1, or on a writable attach, gets requires_materialization = true and can_use_main_thread = true.
  2. PostgresInitGlobalState (src/postgres_scanner.cpp) takes PostgresTransaction::GetConnection() for every such scan. That is one PGconn per transaction.
  3. With requires_materialization, the same function reads the whole relation there: GetLocalState hands the scan the transaction's connection (can_use_main_thread), and ScanChunk runs the binary COPY to the end.
  4. DuckDB initializes the global states of different pipelines on different threads. Two of these scans then run COPY ... TO STDOUT on the one connection at once, and libpq loses the protocol state.

Nothing serializes step 3. OwnedPostgresConnection::connection_lock covers a single Query, not a COPY that spans many reads. PostgresTransaction::GetConnection() also starts the transaction lazily without a lock, so two first callers can both send BEGIN.

Proposed fix

Give PostgresTransaction a mutex that a scan holds for as long as it uses the transaction's connection, and take it in PostgresInitGlobalState whenever the connection comes from the transaction. Held until the function returns, it covers the lazy BEGIN, the materializing COPY, pg_export_snapshot() and a command-only statement:

--- a/src/include/storage/postgres_transaction.hpp
+++ b/src/include/storage/postgres_transaction.hpp
@@ public:
 	PostgresTransactionState GetTransactionState() const {
 		return transaction_state;
 	}
+	mutex &GetConnectionLock() {
+		return connection_lock;
+	}
@@ private:
 	vector<pair<reference<PostgresCatalogSet>, string>> pending_signatures;
+	mutex connection_lock;

--- a/src/postgres_scanner.cpp
+++ b/src/postgres_scanner.cpp
@@ static unique_ptr<GlobalTableFunctionState> PostgresInitGlobalState(
 	optional_ptr<PostgresConnection> con_ptr = nullptr;
 	PostgresPoolConnection pinned_connection;
+	unique_lock<mutex> transaction_connection_guard;
@@
 		auto &transaction = Transaction::Get(context, *pg_catalog).Cast<PostgresTransaction>();
+		transaction_connection_guard = unique_lock<mutex>(transaction.GetConnectionLock());
 		if (bind_data.use_transaction) {

The materializing scans of one statement then read one after another. Scans that stream in parallel use pool connections and do not take the lock past their initialization. With the patch, the reproduction above passed 10 of 10 runs at the default thread count.

Activity

  1. added a commit that references this issue on Nov 29, 2026
    cede84a
  2. added a commit that references this issue on Nov 29, 2026
    a5b9422
  3. staticlibs commented on Nov 29, 2026

    @staticlibs
    Member

    Hi, thanks for the report! While this issue appeared to be not easy to trigger - it is a serious issue. I filed a fix in #676 and published a version of duckdb-postgres with the fix to the core_nightly repo, it can be installed on v2.0.1 using:

    FORCE INSTALL postgres FROM core_nightly;
  4. kenstott commented on Nov 30, 2026

    @kenstott
    Author

    Thank you for the quick fix. We're picking up #676 now and will confirm once our multi-scan workload has run against it.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions