Skip to content

Add pg_lake_remote tables, served by an external query engine - #914

Merged
sfc-gh-agedemenli merged 9 commits into
mainfrom
agedemenli/external-engine-table
Nov 28, 2026
Merged

sfc-gh-agedemenli merged 9 commits into
mainfrom
agedemenli/external-engine-table

Conversation

@sfc-gh-agedemenli

@sfc-gh-agedemenli sfc-gh-agedemenli commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

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.

CREATE SERVER analytics FOREIGN DATA WRAPPER pg_lake_remote
  OPTIONS (conninfo 'host=analytics.internal port=5433 dbname=analytics');
CREATE USER MAPPING FOR app_user SERVER analytics OPTIONS (user 'app_user', password '...');
CREATE FOREIGN TABLE hits (id bigint, url text, event_time timestamptz)
  SERVER analytics OPTIONS (schema_name 'main', table_name 'hits');

SELECT url, count(*) FROM hits GROUP BY url ORDER BY 2 DESC LIMIT 10;  -- runs on the engine

How

  • Wrapper and options: a new pg_lake_remote wrapper reuses pg_lake_table_handler with its own validator, as pg_lake_iceberg does. Its objects are in the 3.7 to 3.8 upgrade script.
    • Servers take a 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.
    • User mappings hold the user, the secrets, and a client certificate and key, which are superuser-only as in postgres_fdw.
    • table_name and schema_name are superuser-only, and table_name is 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.
    • USAGE on the wrapper is granted to no role, so only superusers create servers.
  • Connections:
    • Whose user mapping: a scan uses the user mapping of the user it reads its tables as, as in postgres_fdw: the owner of the view a table came from, or else the current user, falling back to PUBLIC.
    • Passwords: a non-superuser needs a password that the engine asks for, unless a superuser sets password_required 'false'.
    • Client code: connections go through the same client code as pgduck_server's: the same tracking, cleanup on abort, and cancel requests.
    • Interruptible connect: they connect with libpqsrv_connect, so a cancel or statement_timeout interrupts a connection attempt that hangs.
    • Errors name the server.
  • Queries:
    • Pushdown: a query is pushed down whole when all its tables are served by the same engine and read as the same user. Otherwise PostgreSQL plans per-table scans, and EXPLAIN VERBOSE says why.
    • Placeholder: the read_table() placeholder becomes a query on the remote table that selects the columns by name, so the engine may order them differently.
    • Casts: each column of a scalar type is cast to the DuckDB type of its declared type, so an engine INTEGER declared as text is 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.
    • EXPLAIN shows the server, and the plan the engine returns.
  • Read-only:
    • INSERT, UPDATE, DELETE and COPY FROM are already refused, and TRUNCATE is now refused explicitly.
    • INSERT..SELECT into a lake table is no longer pushed down when it reads an engine table, since pgduck_server writes the result on its own connection.
  • deparseRelation no longer honors postgres_fdw's table_name and schema_name options: pg_lake parses the deparsed query again locally, so it has to name the local relation.
  • Docs: docs/external-query-engines.md covers setup, privileges and the risks of password_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:

  • options and privileges, including the refused conninfo options and superuser-only table names;
  • scans, filters, aggregates, joins and set operations pushed down whole;
  • joins with heap and Iceberg tables, and across two servers, which fall back to per-table scans;
  • partitions and inheritance children, views (pushed down unless they mix users), and cursors;
  • column order, and dropped, added and cast columns;
  • read-only refusals, and INSERT..SELECT through a CTE or sublink;
  • prepared statements with generic plans;
  • cancellation, including a connection attempt that hangs;
  • EXPLAIN, dropping the server, table or remote table, and pg_dump.

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

  • Naming: are the names pg_lake_remote, table_name and schema_name right?
  • Function support: pg_lake doesn't check which functions an engine provides. A query using one the engine lacks fails there. Should there be a per-engine gate on what is pushed down?
  • Connections: each scan opens its own connection, and scans don't share a snapshot. Is connection reuse worth adding?

@sfc-gh-mslot

Copy link
Copy Markdown
Collaborator

we might also need #345 for the end-to-end

@sfc-gh-mslot

Copy link
Copy Markdown
Collaborator

CREATE FOREIGN TABLE hits (id bigint, url text, event_time timestamptz)
SERVER analytics OPTIONS (schema_name 'main', table_name 'hits');

can we support hits (/* no column list specified */) syntax here?

@sfc-gh-agedemenli

Copy link
Copy Markdown
Collaborator Author

we might also need #345 for the end-to-end

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?

@sfc-gh-agedemenli

Copy link
Copy Markdown
Collaborator Author

CREATE FOREIGN TABLE hits (id bigint, url text, event_time timestamptz)
SERVER analytics OPTIONS (schema_name 'main', table_name 'hits');

can we support hits (/* no column list specified */) syntax here?

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

@sfc-gh-agedemenli

sfc-gh-agedemenli commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

here it is: #933

@sfc-gh-agedemenli
sfc-gh-agedemenli force-pushed the agedemenli/external-engine-refactor branch from 95205ab to d2711eb Compare November 25, 2026 13:21
@sfc-gh-agedemenli
sfc-gh-agedemenli force-pushed the agedemenli/external-engine-table branch from 065be52 to 1c96aff Compare November 25, 2026 13:22
@sfc-gh-agedemenli
sfc-gh-agedemenli force-pushed the agedemenli/external-engine-refactor branch from d2711eb to 39af319 Compare November 26, 2026 03:23
@sfc-gh-agedemenli
sfc-gh-agedemenli force-pushed the agedemenli/external-engine-table branch from 1c96aff to da2b434 Compare November 26, 2026 03:24
@sfc-gh-agedemenli
sfc-gh-agedemenli force-pushed the agedemenli/external-engine-refactor branch from 39af319 to a06461a Compare November 26, 2026 04:10
@sfc-gh-agedemenli
sfc-gh-agedemenli force-pushed the agedemenli/external-engine-table branch from da2b434 to c6b2cc2 Compare November 26, 2026 04:10

@sfc-gh-mslot sfc-gh-mslot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Base automatically changed from agedemenli/external-engine-refactor to main November 27, 2026 08:39
@sfc-gh-agedemenli
sfc-gh-agedemenli force-pushed the agedemenli/external-engine-table branch from e371e44 to 8aa2ca7 Compare November 27, 2026 08:44
sfc-gh-agedemenli and others added 6 commits November 27, 2026 14:30
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>
sfc-gh-agedemenli and others added 3 commits November 27, 2026 14:30
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>
@sfc-gh-agedemenli
sfc-gh-agedemenli force-pushed the agedemenli/external-engine-table branch from 8aa2ca7 to c335c6e Compare November 27, 2026 11:32

@sfc-gh-mslot sfc-gh-mslot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@sfc-gh-agedemenli
sfc-gh-agedemenli merged commit 1800294 into main Nov 28, 2026
90 checks passed
@sfc-gh-agedemenli
sfc-gh-agedemenli deleted the agedemenli/external-engine-table branch November 28, 2026 08:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants