Skip to content

Remote pushdown: reads that use binary COPY cost four round trips (Parse, Describe, Close, then COPY) #664

Backlog

Description

@SeekoeiD

What happens?

On 2.0.1, remote pushdown hands a translated query to postgres_query. Binding it calls PQprepare (Parse + Sync) and PQdescribePrepared (Describe + Sync). With the default query mode the result is then read with a simple-query COPY (...) TO STDOUT (FORMAT binary), which does not use the prepared statement, so the binary reader first calls PQclosePrepared (Close + Sync). Each of those libpq calls waits for its reply, so a pushed-down read costs four round trips where a plain COPY costs one.

On a DuckLake catalog in Postgres this makes commits slower than on 2.0.0, although 2.0.1 sends fewer metadata queries. In the script below, one steady-state commit that inserts into four tables makes these exchanges, from the first SELECT 1 connection check through DISCARD ALL, not counting the marker connection:

metadata COPY requests before the write batch client round trips
2.0.0 (ducklake 417a9117f5, postgres_scanner c0f5a3c) 11; the first (the snapshot query) is prepared as the unnamed statement: Parse, Describe, no Close 19
2.0.1 (ducklake 08089b16dc, postgres_scanner 8b9d0bb), default settings 6, each after Parse, Describe and Close 30
2.0.1 with SET pg_enable_remote_pushdown = false before the ATTACH 11; the first after Parse, Describe and Close 20

Each total includes six other exchanges: two SELECT 1, BEGIN, the write batch, COMMIT and DISCARD ALL.

We also measured this separately on Linux, with netem delay on a Postgres 18.6 container and a larger write than this script's. Postgres ran each statement in under a millisecond. At 176 ms round-trip time a commit took 3.4 s on 2.0.0 and 5.9 s on 2.0.1 (packet captures counted 18 against 32 round trips), and 3.4 s on 2.0.1 with remote pushdown off. At 8 ms it was 186 ms against 300 ms. The timing differences at both latencies fit those 14 extra round trips.

As far as I can tell it comes from two changes that are both in 2.0.1 and not in 2.0.0:

  • Support reusing Postgres prepared statements #640 gave postgres_query named statements (duckdb_stmt_N) so they can be reused. 2.0.0 prepared and described the unnamed statement and never closed it. When the result is read with COPY, the named statement is never executed, and closing it is one more round trip. You can see this on the snapshot query, which went through postgres_query in 2.0.0 already: three round trips there, four in 2.0.1.
  • Implement support for RemotePushdownOptimizer #643 routes eligible translated queries through postgres_query. In this commit the two stats scans of 2.0.0 become one pushed-down stats query, and the four pairs of schema and table path scans become four pushed-down path lookups. Each of those five now carries the prepare, describe and close.

Code, pinned at 589a687 on main. These call sequences are unchanged from 2.0.1:

  • the prepare and describe in bind:
    // prepare execution of the query to figure out the result types and names
    string stmt_name = PostgresPreparedStatement::GenerateName();
    if (PostgresConnection::DebugPrintQueries()) {
    Printer::Print("PREPARE " + stmt_name + ": " + sql + "\n");
    }
    PGresult *prepared_res_ptr = PQprepare(conn, stmt_name.c_str(), sql.c_str(), 0, nullptr);
    auto prepared = make_uniq<PostgresPreparedStatement>(conn, pool_connection_id, stmt_name, sql, prepared_res_ptr);
    // use describe_prepared
    auto describe_prepared = PQdescribePrepared(conn, prepared->GetName().c_str());
    PostgresResult describe_wrapper(describe_prepared);
    if (!describe_prepared || PQresultStatus(describe_prepared) != PGRES_COMMAND_OK) {
    auto extended_err = PostgresUtils::GetErrorMessage(describe_prepared, conn);
    throw BinderException("Failed to describe prepared statement: %s", extended_err);
    }
    conn_lock.unlock();
  • the Close before COPY:
    } else {
    // COPY does not use the statement, it must be closed before the connection enters the COPY state
    DestroyPreparedStatement();
    con.BeginCopyFrom(context, sql, PGRES_COPY_OUT);
    and
    return;
    }
    // mark the statement as destroyed even if closing fails, so it is never executed again
    destroyed = true;
    auto conn_lock = con.Lock();
    auto conn = con.GetConn();
    PostgresResult close_result(PQclosePrepared(conn, name.c_str()));
    if (!close_result.res || PQresultStatus(close_result.res) != PGRES_COMMAND_OK) {
    auto error = PostgresUtils::GetErrorMessage(close_result.res, conn);
    throw std::runtime_error(
    StringUtil::Format("Failed to close prepared statement \"%s\": %s", name, string(error)));
    }
  • pushdown handing the SQL to postgres_query:
    PostgresWriterResult query;
    try {
    query = PostgresSQLWriter::WriteQuery(context, *this, *node, &bound.types);
    } catch (PostgresPushdownNotSupported &ex) {
    // the query contains a construct that cannot be translated for the types it operates on
    if (PostgresConnection::DebugPrintQueries()) {
    Printer::Print("Remote pushdown: executing locally, " + string(ex.what()));
    }
    return PostgresExecuteLocally(std::move(local_node));
    }
    auto preliminary_queries = GetRemotePushdownPreliminaryQueries(context, query.requires_time_zone);
    for (auto &preliminary_query : query.preliminary_queries) {
    preliminary_queries.push_back(std::move(preliminary_query));
    }
    vector<unique_ptr<ParsedExpression>> args;
    args.push_back(ConstantExpression::FromValue(Value(GetName())));
    args.push_back(ConstantExpression::FromValue(Value(query.sql)));
    if (!preliminary_queries.empty()) {
    vector<Value> preliminary_values;
    for (auto &preliminary_query : preliminary_queries) {
    preliminary_values.emplace_back(preliminary_query);
    }
    args.push_back(make_uniq<ComparisonExpression>(
    ExpressionType::COMPARE_EQUAL, make_uniq<ColumnRefExpression>("preliminary_queries"),
    ConstantExpression::FromValue(Value::LIST(LogicalType::VARCHAR, std::move(preliminary_values)))));
    }
    // let DuckDB check that the transaction can read from / write to the database
    args.push_back(make_uniq<ComparisonExpression>(
    ExpressionType::COMPARE_EQUAL, make_uniq<ColumnRefExpression>("modifies_database"),
    ConstantExpression::FromValue(Value::BOOLEAN(PostgresIsDML(*node)))));
    if (PostgresIsDMLWithoutReturning(*node)) {
    // the statement yields the number of changed rows
    args.push_back(make_uniq<ComparisonExpression>(ExpressionType::COMPARE_EQUAL,
    make_uniq<ColumnRefExpression>("return_changed_rows"),
    ConstantExpression::FromValue(Value::BOOLEAN(true))));
    }
    auto func_ref = make_uniq<TableFunctionRef>();
    func_ref->function = make_uniq<FunctionExpression>("postgres_query", std::move(args));
    func_ref->alias = Identifier("postgres_query");

Expected: a pushed-down read costs about what the COPY statements it replaces cost. Some options, though I don't know all the constraints:

  • on the path that is certain to read with COPY, use the unnamed statement as 2.0.0 did, which saves the Close without touching the reuse from Support reusing Postgres prepared statements #640 on the plain-query path;
  • send Parse and Describe behind one Sync (libpq pipeline mode), which saves another round trip; Feature Request: Allow for libpq pipeline mode #649 asks for pipeline mode for other reasons;
  • for translated reads whose Postgres result columns can be derived reliably, skip the describe and keep it as the fallback.

With pg_enable_remote_pushdown = false this script drops to 20 round trips, but the setting turns off whole-query pushdown for every query on that attachment. On a DuckLake catalog that includes the stats lookup in duckdb/ducklake#1976: with pushdown off, 2.0.1 runs it as separate scans again, one of which copies data_file_id and end_snapshot for every live data file with no table filter. In that issue's two-writer script, with pushdown off on 2.0.1, it ran on every insert that followed the other writer's commit. So for us the setting is not a clean workaround.

To Reproduce

One DuckLake writer on a Postgres catalog, three commits that each insert into four tables. Count the parse lines against the COPY lines between two markers in the Postgres log.

# pip install duckdb==2.0.1 (the first run downloads the ducklake and postgres extensions)
# A scratch Postgres that logs every statement and every parse:
#   docker run -d --name pg -e POSTGRES_HOST_AUTH_METHOD=trust -p 127.0.0.1:5432:5432 postgres:17 \
#     -c log_statement=all -c log_min_duration_statement=0
# Wait until it accepts connections, then run with duckdb 2.0.0: python repro.py on
# and with duckdb 2.0.1: python repro.py on   and   python repro.py off
#   docker logs pg 2>&1 | grep -E "marker:|parse (duckdb_stmt_|<unnamed>)|statement: COPY"
import os
import sys
import tempfile
import time
import uuid

import duckdb

PUSHDOWN = sys.argv[1] if len(sys.argv) > 1 else 'on'
PG = os.environ.get('PGCONN', 'host=127.0.0.1 port=5432 user=postgres dbname=postgres')
DATA = tempfile.mkdtemp()
SCHEMA = 'rt_' + uuid.uuid4().hex[:8]

setup = duckdb.connect()
setup.sql('INSTALL ducklake; INSTALL postgres; LOAD postgres')
setup.sql(f"ATTACH '{PG}' AS pg (TYPE postgres)")
setup.sql(f"CALL postgres_execute('pg', 'CREATE SCHEMA {SCHEMA}')")


def mark(text):
    # a statement that shows up in the Postgres log between the steps
    setup.sql(f"CALL postgres_execute('pg', 'SELECT ''marker: {text}''')")


con = duckdb.connect()
con.sql('LOAD ducklake; LOAD postgres')

if PUSHDOWN == 'off':
    con.sql('SET pg_enable_remote_pushdown = false')  # before the ATTACH

con.sql(f"ATTACH 'ducklake:postgres:{PG}' AS lake "
        f"(DATA_PATH '{DATA}', METADATA_SCHEMA '{SCHEMA}', DATA_INLINING_ROW_LIMIT 0)")

print(con.execute('SELECT version()').fetchone()[0],
      con.execute("SELECT extension_name, extension_version FROM duckdb_extensions() "
                  "WHERE extension_name IN ('ducklake', 'postgres_scanner')").fetchall(),
      'pushdown', PUSHDOWN)

for name in ('a', 'b', 'c', 'd'):
    con.sql(f'CREATE TABLE lake.{name}(id BIGINT, s VARCHAR)')

for i in range(3):
    mark(f'commit {i} ({PUSHDOWN})')
    con.sql('BEGIN')

    for name in ('a', 'b', 'c', 'd'):
        con.sql(f"INSERT INTO lake.{name} SELECT range, 'x' FROM range(1000)")

    t = time.perf_counter()
    con.sql('COMMIT')
    print(f'commit {i}: COMMIT {(time.perf_counter() - t) * 1000:.0f} ms')

mark('end')
print(f'to clean up: DROP SCHEMA {SCHEMA} CASCADE in Postgres, and delete {DATA}')

From the parse line of marker: commit 1 up to the parse line of marker: commit 2, the log has these counts, which include the first marker's own parse and COPY:

                     parse lines   COPY lines
2.0.0                          2           12
2.0.1                          7            7
2.0.1 pushdown off             2           12

The Postgres log shows the Parse but not the Describe or the Close. To see those I ran the same script through a small proxy that forwards the bytes and logs each frontend message. This is the client side of commit 1 on 2.0.1 with default settings, one line per client flight (each line waits for the server's reply before the next is sent), SQL shortened:

Query SELECT 1
Query BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ
Parse duckdb_stmt_33 SELECT snapshot_id, schema_version, next_catalog_id, ... | Sync
Describe S:duckdb_stmt_33 | Sync
Close S:duckdb_stmt_33 | Sync
Query COPY (SELECT snapshot_id, schema_version, next_catalog_id, ...) TO STDOUT (FORMAT "binary")
Parse duckdb_stmt_34 SELECT "table_id", "column_id", "record_count", "next_row_id", ... | Sync
Describe S:duckdb_stmt_34 | Sync
Close S:duckdb_stmt_34 | Sync
Query COPY (SELECT "table_id", "column_id", "record_count", "next_row_id", ...) TO STDOUT (FORMAT "binary")
Parse duckdb_stmt_35 SELECT "t"."table_id", "s"."path" AS "s_path", ... | Sync
Describe S:duckdb_stmt_35 | Sync
Close S:duckdb_stmt_35 | Sync
Query COPY (SELECT "t"."table_id", "s"."path" AS "s_path", ...) TO STDOUT (FORMAT "binary")
... the same four lines for duckdb_stmt_36, 37 and 38 (one per table)
Query SET LOCAL extra_float_digits = 3;INSERT INTO ... (the write batch)
Query COMMIT
Query SELECT 1
Query DISCARD ALL

The same commit on 2.0.0:

Query SELECT 1
Query BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ
Parse (unnamed) SELECT snapshot_id, schema_version, next_catalog_id, ... | Sync
Describe S:(unnamed) | Sync
Query COPY (SELECT snapshot_id, schema_version, next_catalog_id, ...) TO STDOUT (FORMAT "binary")
Query COPY (SELECT "table_id", "record_count", "next_row_id", "file_size_bytes" FROM ...ducklake_table_stats ...)
Query COPY (SELECT "table_id", "column_id", "contains_null", ... FROM ...ducklake_table_column_stats ...)
Query COPY (SELECT "schema_id", "path", "path_is_relative" FROM ...ducklake_schema ...)
Query COPY (SELECT "schema_id", "table_id", "path", "path_is_relative" FROM ...ducklake_table ...)
... the same two COPY statements for each of the other three tables
Query SET LOCAL extra_float_digits = 3;INSERT INTO ... (the write batch)
Query COMMIT
Query SELECT 1
Query DISCARD ALL

Round trips per commit, from the proxy log (commit 0 also loads the catalog, so it is larger on every version):

                   commit 0   commit 1   commit 2
2.0.0                    35         19         19
2.0.1                    53         30         30
2.0.1 pushdown off       36         20         20

2.0.0 does not have pg_enable_remote_pushdown, so python repro.py off fails there with an unknown-setting error.

OS:

Windows 11, x86_64 (DuckDB client). Postgres in Docker on the same machine. The latency numbers come from Linux x86_64 clients against Postgres 18.6 in Docker, with netem delay on the Postgres container.

PostgreSQL Version:

17.11 (postgres:17 image) for the script and trace. 18.6 for the latency measurements.

DuckDB Version:

2.0.0 and 2.0.1

DuckDB Client:

Python 3.12.10

Full Name:

Daniël du Toit

Affiliation:

silversixpence-crypto

Have you tried this on the latest main branch?

  • I agree

I tested the 2.0.0 and 2.0.1 releases and did not build main. The code linked above is unchanged on main at 589a687.

Have you tried the steps to reproduce? Do they include all relevant data and configuration? Does the issue you report still appear there?

  • I agree

🤖 Written by Claude Code on behalf of @SeekoeiD.

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