Repository navigation
Add pg_lake_remote tables, served by an external query engine - #914
Conversation
df6f29f to
95205ab
Compare
a584188 to
065be52
Compare
|
we might also need #345 for the end-to-end |
can we support |
looks like that PR is about writes when postgres and pgduck_server don't share a filesystem. Here the remote tables are actually read-only. And rows come back over the connection without involving any temp files. Do you have another part in your mind? |
Sure, we can do it like for files: run DESCRIBE on the engine and map the types the same way. Mind if I do it in a follow-up PR on top of this one? This one's already big |
|
here it is: #933 |
95205ab to
d2711eb
Compare
065be52 to
1c96aff
Compare
d2711eb to
39af319
Compare
1c96aff to
da2b434
Compare
39af319 to
a06461a
Compare
da2b434 to
c6b2cc2
Compare
sfc-gh-mslot
left a comment
There was a problem hiding this comment.
Nice work, the option and privilege rules match postgres_fdw closely, and I couldn't get any remote-table SQL to reach pgduck_server or any file read through a non-superuser path. Two things from testing locally: external connections don't get the session TimeZone, so timestamptz expressions give wrong results, and the cancel on abort can leave a backend stuck for good when the engine stops answering.
|
|
||
| Oid userId = OidIsValid(queryEngine.userId) ? queryEngine.userId : GetUserId(); | ||
|
|
||
| return GetExternalEngineConnection(queryEngine.serverId, userId); |
There was a problem hiding this comment.
setSessionTimeZone is dropped here, so the engine evaluates timestamptz expressions in its own zone. With SET TimeZone 'Asia/Tokyo' and t = '2024-01-01 20:00+00', the remote table gives t::date = 2024-01-01 and extract(hour) = 20, while the same data in heap or Iceberg gives 2024-01-02 and 5. The FDW path is affected too: WHERE t::date = '2024-01-02' returns no rows.
Could the external connection go through the same SET TimeZone as pgduck_server, and the doc list it as something an engine has to support?
There was a problem hiding this comment.
Right, that's what #915 does: it's stacked on this one and sets the session TimeZone on external connections the same way, with the docs listing current_setting('TimeZone') and SET TimeZone as engine requirements. We'll merge the two back to back.
| * ConnectToExternalQueryEngine and releases its file descriptor. | ||
| */ | ||
| void | ||
| DisconnectFromExternalQueryEngine(PGconn *connection) |
There was a problem hiding this comment.
On abort, ReleaseAllPGDuckConnections calls CancelRunningCommandOnConnection, which uses blocking PQcancel with no timeout. With an engine that accepts the cancel connection but never answers, a ROLLBACK after FETCH 1 from a cursor hung for good. pg_terminate_backend didn't free it, so only SIGKILL (and with it a cluster restart) did.
Maybe add a cancel helper here using libpqsrv_cancel(conn, endtime) on PG 17+, as postgres_fdw does?
There was a problem hiding this comment.
Good catch, thanks. Done in e371e44: from PG 17 the cancel goes through libpqsrv_cancel with the cleanup timeout, as in postgres_fdw, via a helper in external_connection.c. PG 16 has no cancel with a timeout, so it keeps PQcancel. There's a test with a proxy that never answers cancel requests: the ROLLBACK after FETCH 1 now finishes at the timeout.
e371e44 to
8aa2ca7
Compare
Add a foreign data wrapper for tables that are served by an external query engine: a server that speaks the PostgreSQL wire protocol and runs DuckDB SQL, like pgduck_server does. It reuses pg_lake_table_handler, so these tables get the same scan code as other pg_lake tables, and has its own validator, the way pg_lake_iceberg does. A server has a conninfo option. Every role can read the options of a server, so as in postgres_fdw the conninfo may not contain the user, the options that libpq marks as secret (password, sslpassword and, in PostgreSQL 18, oauth_client_secret) or libpq's debug options such as replication and sslkeylogfile. User mappings hold the user and the secrets, a client certificate and key (sslcert and sslkey, which name files on this server and are superuser-only, as in postgres_fdw), and password_required, which only a superuser can set to false. Foreign tables name the table on the engine with table_name and, optionally, schema_name. Both are superuser-only and table_name is required: DuckDB reads a table name that is not in its catalog as a file or URL, with the engine's access to the file system and object storage, so whoever sets the name decides what any reader of the table reads, bypassing the checks pg_lake makes for files. The name of the foreign table is not used instead, since its owner can rename it. USAGE on the wrapper is not granted to any role, so only superusers can create servers. Signed-off-by: Ahmet Gedemenli <ahmet.gedemenli@snowflake.com> Co-authored-by: Cursor <cursoragent@cursor.com>
GetQueryEngineConnection can now open a connection to an external query engine, identified by its pg_lake_remote foreign server. The conninfo is the server's conninfo option followed by the libpq options of the user mapping: the user, the secrets and the client certificate. A user mapping is optional, since an engine may not need credentials. The user mapping is the one of the user that the scan reads its tables as, as in postgres_fdw: the owner of the view that a table was expanded from, or else the current user, falling back to the PUBLIC mapping. An FDW scan gets that user from the plan's checkAsUser, and the full query pushdown scan from the permission info of the first engine table in its query. EXPLAIN connects as the same user. As in postgres_fdw, a non-superuser must have a password in the user mapping and the engine must ask for it, unless a superuser set password_required to false on the mapping. Otherwise a role could use the engine's trust authentication, or the password file of the server's operating system user, under a remote user name of its choosing. The connection goes through the same client code as pgduck_server connections, so it is tracked in the same hash, closed on (sub)transaction abort, and cancelled with a CancelRequest. Unlike pgduck_server's local socket, the engine may be on another host, so we connect with libpqsrv_connect, which a cancel request or statement_timeout can interrupt, and which reserves the file descriptor like postgres_fdw does. pgduck_server connections are unchanged. Unlike pgduck_server connection failures, which are hidden from users, a failed connection to an external engine reports the server name and the libpq error, since users configure these servers. Errors that the engine returns name the server in their context, and EXPLAIN says so when an engine does not return a DuckDB plan. Signed-off-by: Ahmet Gedemenli <ahmet.gedemenli@snowflake.com> Co-authored-by: Cursor <cursoragent@cursor.com>
A foreign table of the pg_lake_remote wrapper is now served by the external query engine of its server, whose Oid identifies the engine. The planner hook, the shippability walker and the read_table() placeholder walker treat these tables like pg_lake tables, and the full query pushdown and FDW scans send their SQL to that engine. The read_table() placeholder of such a table becomes a query on the remote table, named by the table_name and schema_name options. It selects the columns by name, in the order of the foreign table: the deparsed query gives read_table() a column alias list, which renames columns by position, and the engine may order them differently. EXPLAIN shows this query too, since it is short and names the remote table. The query casts each column of a scalar type to the DuckDB type of its declared type, so that the engine computes with the declared type even if its column has another one: otherwise an engine INTEGER column declared as text would be compared and sorted as an integer, with no error. DuckDB drops a cast to the type a column already has, so on pgduck_server a filter on such a column still reaches the table scan as a table filter. A filter on a column of another type is still applied by the scan, as an expression, without the column's statistics. We do not cast types without an exact DuckDB type, such as numeric without a precision, nor geometry, arrays, composite types and maps, which DuckDB casts unlike how PostgreSQL reads their text. A query can only be sent to one engine, as one user, so full query pushdown now also requires that all tables are served by the same engine and, for an external engine, are read as the same user, which differs for a table in a view of another owner. Otherwise PostgreSQL plans the query over per-table scans. The FDW path already only joins tables of the same server and user. EXPLAIN VERBOSE lists a table on another engine or read as another user among the constructs that are not vectorized. The scan snapshot has no files for these tables, and EXPLAIN shows the server that runs the query instead of the files it scans. deparseRelation no longer honors table_name and schema_name: unlike in postgres_fdw, we parse the deparsed query again locally, so it has to name the local relation. No other pg_lake table accepts these options. Signed-off-by: Ahmet Gedemenli <ahmet.gedemenli@snowflake.com> Co-authored-by: Cursor <cursoragent@cursor.com>
INSERT, UPDATE and DELETE on these tables, and COPY FROM into them, are already refused by PostgreSQL, since postgresIsForeignRelUpdatable only reports writable lake tables as updatable. TRUNCATE has no such check and would try to remove the table's data files, so refuse it explicitly. INSERT..SELECT pushdown into a lake table runs the SELECT on the same connection that pgduck_server uses to write the result as files, so it now requires that the query reads no table of an external query engine. Otherwise PostgreSQL runs the INSERT..SELECT: it reads from the engine through the FDW and inserts through the lake table's FDW, which is correct, only slower. Signed-off-by: Ahmet Gedemenli <ahmet.gedemenli@snowflake.com> Co-authored-by: Cursor <cursoragent@cursor.com>
Most tests use the test pgduck_server as the external query engine: they create DuckDB tables in its database, a pg_lake_remote server whose conninfo points at it, and foreign tables over those tables. They cover the options of servers, user mappings and tables, including the secret and debug libpq options that a server conninfo refuses, the TLS options of user mappings, and that only superusers can set table_name and schema_name; scans, filters, aggregates, joins and set operations pushed down whole; joins with a heap table and with an Iceberg table, between tables of two servers, and partitions and inheritance children on the engine, which fall back to per-table scans; views, which are pushed down whole unless they mix users; cursors, including scrollable and holdable ones; columns in a different order on the engine, dropped and added columns, and columns cast to their declared types, with filters still applied by the engine's scan; refusal of INSERT, UPDATE, DELETE, COPY FROM and TRUNCATE, and INSERT..SELECT into an Iceberg table, also through a CTE or a sublink, without pushdown; prepared statements with generic plans; cancellation, once the query waits for the engine, and interrupting a connection attempt that hangs; EXPLAIN; the password rules for non-superusers and the quoting of credentials; dropping the server, the foreign table and the remote table; and pg_dump. Other tests use the test PostgreSQL server as the engine, with remote users that authenticate with a password. They check that the user and password of the user mapping reach the engine, that a view reads its engine tables with the user mapping of its owner, that errors from the engine and an EXPLAIN it cannot answer name the server, and that a cancel stops the query on the engine. Signed-off-by: Ahmet Gedemenli <ahmet.gedemenli@snowflake.com> Co-authored-by: Cursor <cursoragent@cursor.com>
Add a page for pg_lake_remote tables to the user guide: how to set up a server, user mappings and foreign tables, the privileges involved and the risks of password_required 'false', how queries are sent to the engine, how columns are matched and cast, what an engine has to provide, and the limitations. Signed-off-by: Ahmet Gedemenli <ahmet.gedemenli@snowflake.com> Co-authored-by: Cursor <cursoragent@cursor.com>
From PostgreSQL 19, libpq-be-fe-helpers.h includes libpq-be-fe.h, which redefines PGresult, and the libpq functions that take one, as a memory-context-safe wrapper in every file that includes it. client.c included it for libpqsrv_connect, so on PostgreSQL 19 its functions handed wrapped results to callers that expect plain ones, and the cache worker crashed reading them. Move libpqsrv_connect and libpqsrv_disconnect to external_connection.c, which handles no results. Co-authored-by: Cursor <cursoragent@cursor.com> Signed-off-by: Ahmet Gedemenli <ahmet.gedemenli@snowflake.com>
installcheck moves pgduck_server to another port after the test module is imported, so the conninfo built at import pointed at the port of the check target and the tests could not reach the engine. Co-authored-by: Cursor <cursoragent@cursor.com> Signed-off-by: Ahmet Gedemenli <ahmet.gedemenli@snowflake.com>
On abort, the command still running on a connection is cancelled with PQcancel, which waits for the server without a timeout. An external query engine that accepts the cancel request but never answers left the backend waiting for good, beyond the reach of pg_terminate_backend. From PostgreSQL 17, send the cancel request with libpqsrv_cancel, which gives up at the cleanup timeout, as postgres_fdw does. It is called from external_connection.c, the one file that may include libpq-be-fe-helpers.h. PostgreSQL 16 has no cancel request with a timeout, so it keeps PQcancel. Co-authored-by: Cursor <cursoragent@cursor.com> Signed-off-by: Ahmet Gedemenli <ahmet.gedemenli@snowflake.com>
8aa2ca7 to
c335c6e
Compare
sfc-gh-mslot
left a comment
There was a problem hiding this comment.
Thanks, the cancel now gives up after the cleanup timeout. My proxy repro rolls back in 30s instead of hanging. Fine with the TimeZone fix landing in #915.
One note for later: each scan opens its own connection, which is fine for an engine on a local socket. To run pgduck_server remotely or over the network in production, we'd also need to cache connections (per server and user mapping, like postgres_fdw), so that every scan doesn't pay for a TCP and TLS handshake and authentication.
pg_lake runs every query in pgduck_server. This PR lets a foreign table be served by another server instead, an external query engine: any server that speaks the PostgreSQL wire protocol and runs DuckDB SQL, the way pgduck_server does. PostgreSQL still plans the query, and pg_lake's rewrite and pushdown rules still generate the DuckDB SQL. The only difference is where it is sent. Stacked on #913.
How
pg_lake_remotewrapper reusespg_lake_table_handlerwith its own validator, aspg_lake_icebergdoes. Its objects are in the 3.7 to 3.8 upgrade script.conninfo. As in postgres_fdw, it cannot hold the user, the options libpq marks as secret, or libpq's debug options, since every role can read server options.table_nameandschema_nameare superuser-only, andtable_nameis required. DuckDB reads a table name it does not know as a file or URL, with the engine's access to its file system and object storage, so whoever sets the name decides what every reader of the table reads.PUBLIC.password_required 'false'.libpqsrv_connect, so a cancel orstatement_timeoutinterrupts a connection attempt that hangs.read_table()placeholder becomes a query on the remote table that selects the columns by name, so the engine may order them differently.INTEGERdeclared astextis compared and sorted as text. DuckDB drops a cast to a column's own type, so filters on matching columns still reach the engine's scan.deparseRelationno longer honors postgres_fdw'stable_nameandschema_nameoptions: pg_lake parses the deparsed query again locally, so it has to name the local relation.docs/external-query-engines.mdcovers setup, privileges and the risks ofpassword_required 'false', query routing and column casts, what an engine has to provide, and the limitations.Tests
test_external_engine_table.py, mostly with the test pgduck_server acting as the external engine, covers:Tests with a plain PostgreSQL server as the engine check that credentials reach it, that views use their owner's mapping, and that errors name the server.
The existing pushdown, FDW, EXPLAIN, prepared statement, join, CTE, view, partition, INSERT..SELECT and create/drop extension tests also pass.
Open questions
pg_lake_remote,table_nameandschema_nameright?