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

Aperta
#664 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
42/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
cpp, postgresql

Direzione di ricerca

Start by reading the bind path in src/postgres_query.cpp (lines 234-248) alongside the Close in src/postgres_binary_reader.cpp (31-34) and src/postgres_prepared_statement.cpp (47-58); the pushdown entry point is src/storage/postgres_catalog.cpp (298-336). Reproduce with the attached Python script against a Postgres logging log_statement=all, counting parse against COPY lines between markers and using the proxy trace to see Describe/Close. Done means a pushed-down read costs one round trip like a plain COPY, with the same commit round-trip counts as 2.0.0 or fewer.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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 c0f5a3c0c4) 11; the first (the snapshot query) is prepared as the unnamed statement: Parse, Describe, no Close 19
2.0.1 (ducklake 08089b16dc, postgres_scanner 8b9d0bbe8d), 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:

  • #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.
  • #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 589a6871 on main. These call sequences are unchanged from 2.0.1:

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 #640 on the plain-query path;
  • send Parse and Describe behind one Sync (libpq pipeline mode), which saves another round trip; #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 https://github.com/duckdb/ducklake/issues/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 589a6871.

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.

Lingua principale
C++
Stelle
380
Fork
122
Merge medio
2h 17m
PR unite (30g)
18

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di duckdb/duckdb-postgres

Tutte le issue di duckdb/duckdb-postgres

Issue simili

Altre issue su C++

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.