Skip to content

feat: opt-in predicate pushdown for ENGINE = SQL external tables - #27710

Merged
fengttt merged 11 commits into
matrixorigin:mainfrom
fengttt:feat-sql-exttab-pushdown
Aug 27, 2026
Merged

fengttt merged 11 commits into
matrixorigin:mainfrom
fengttt:feat-sql-exttab-pushdown

Conversation

@fengttt

@fengttt fengttt commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Note: this body describes the current contract. The design changed twice during review; see History for what changed and why.

Contract

select * from ext_sql_tab where id > 3 sends the __mo_query text to the source verbatim and filters locally, so the whole source crosses the wire before MO drops rows. A table can opt into having the source do the narrowing:

create external table orders (id bigint, name varchar(64))
engine = sql with ('config' = '...', 'pushdown' = 'true');

compileForeignScan then renders the row-level conjuncts and wraps each query text as a derived table:

select * from (
select id, name from src
) __mo_subq_1a2b3c4d where (id > 3)

Three rules, and no others:

  1. Always push. An opted-in table sends every conjunct MO can render. No probing, no capability negotiation, no per-query decision.
  2. A source error is the error. No second, unfiltered attempt.
  3. On success the columns must be the declared ones, compared in order and case-insensitively, or that is an error.

Exactly the rendered conjuncts leave node.FilterList — the source owns them. Anything unrenderable stays local.

Why rule 3 exists

A foreign scan maps the result positionally and never reads the source's column names, so select a_id, a_name from src may legitimately feed columns declared (id, name). A WHERE clause has to name what it filters, and the only names MO has are its own. Opting in is therefore a statement about the source — that its result columns are the table's. MO checks that claim rather than trusting it: database/sql reports the column names the moment the query returns, before any row is read, so the check costs nothing.

A mismatch has to be an error rather than a fallback: the source has already run a query MO narrowed, and MO cannot tell whether the rows it is about to read were filtered on the columns it meant.

Tables that do not opt in are untouched — positional mapping, verbatim query.

Identifiers

Written bare. The quoting character is dialect-specific (MySQL backticks, standard double quotes) while a bare identifier is accepted by both, and sql_tvf speaks to PostgreSQL as well as MySQL. isBareIdentifier requires [A-Za-z_][A-Za-z0-9_]* and refuses the union of the words MySQL 8.0 and PostgreSQL reserve, so a column called order keeps its conjunct local rather than producing SQL no dialect parses. Refusing on the union is deliberate: the renderer does not know which source the text is bound for, and refusing costs only the optimization.

The derived-table alias is MO's own (__mo_subq_ + crc32 hex), spelled from [a-z0-9_], so it needs no quoting either.

One dialect difference is stated rather than hidden: the declared-column check is case-insensitive, which matches MySQL, where a bare id resolves against a column projected as ID. PostgreSQL folds unquoted id to lower case and will not match AS "ID", so there such a query fails at the source before the check runs. Project lower-case aliases on PostgreSQL.

Why opt-in

A pushed predicate is not provably superset-preserving across engines: the source may drop a row MO would have kept under a different collation, time zone, or coercion, and nothing MO does afterwards can bring it back. Same reasoning as DATASTREAM's recheck. Wrapping adds two more effects a table has to ask for: a text that is a valid statement but an invalid derived table (SHOW, CALL, duplicate projected names) now fails, and an ORDER BY inside a derived table is not guaranteed to survive.

Compatibility: the option defaults to false, an envelope written before it existed decodes to false, the plan field's zero value is "verbatim", and SHOW CREATE renders "pushdown" only when a table opted in.

History (what changed during review, and why)

  1. 'recheck' = 'false', no local recheck. Filtered on MO's declared names, which broke the positional contract: a source with no column of that name got where id > 3. It also rendered MySQL-quoted identifiers at any driver, including PostgreSQL.
  2. Probe + source-name mapping, filters kept local. Probed ... LIMIT 0 for the source's names and rendered in its vocabulary, with fallback to verbatim everywhere. Correct, but a round trip per query and a capability interface, to discover a contract instead of stating one.
  3. Current. Fix the contract (rule 3) and the discovery machinery disappears: the names come free with the result, the probe and the PushdownProber capability are deleted, rendering returns to compile, and identifiers go bare so both drivers are served. −132 lines against (2).

Testing

  • pkg/sql/foreignext — wrapper shape, alias determinism and its [a-z0-9_] alphabet, ;/line-comment tails, option parsing (SQL-only, bool-only, kind-aware help text), envelope round-trip including a legacy envelope with no pushdown field.
  • pkg/sql/datastream — bare vs quoted rendering; reserved words (order, select, user, limit, mixed case) refused; words reserved by only one dialect (variadic, ilike, zerofill, rlike) refused for both; sql-ish but legal names (status, orders, selected) still pushed; string literals keep their own quoting.
  • pkg/sql/compile — default sends verbatim; opted in wraps and trims exactly the pushed conjunct; unrenderable conjuncts stay local; nothing renderable ⇒ no wrapper; ESQL never wraps; a synthetic-column predicate is never sent.
  • pkg/sql/colexec/external — the column check for exact match, case-insensitive match, wrong order, arity mismatch, a connection that cannot report columns, and pruned scans (a scan reading one column of four still knows the table is four wide and checks its own column at its own position — the check reads ColumnListLen and ColFieldIndex, which survive pruning).
  • BVT function/foreign_exttab_pushdown.sql — identical answers with and without pushdown, IS NULL/LIKE/BETWEEN/IN/OR, unrenderable conjuncts, query tails, IN-derived query lists, the 'query' option, SHOW CREATE, the column check and its case-insensitivity, and option validation.
  • Live: EXPLAIN ANALYZE on a 100-row source through a table declared (id, name) over source columns (a_id, a_name) — external scan inputRows=1 (84 bytes) with pushdown against inputRows=100 (8.20 KiB) without, same answer.

Known gap: BVT exercises MySQL only, because the harness has no PostgreSQL source. PostgreSQL behaviour is covered by unit tests (bare rendering, reserved-word refusal) and stated in the docs, not by public-path BVT.

Docs: docs/cn/esql_sql_exttab.md §2.4–2.5.

🤖 Generated with Claude Code

https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6

A SELECT over a foreign SQL external table sent the user's __mo_query text
verbatim and applied every other predicate locally, so `where id > 3`
transferred the whole source before dropping rows. This adds pushdown for
ENGINE = SQL: the query text becomes a derived table carrying the conjuncts
MO can deparse.

    select * from (
    <__mo_query text>
    ) `__mo_subq_<hash>` where (`id` > 3)

Exactly the deparsed conjuncts leave node.FilterList; the rest stay local.
The deparser is DATASTREAM's (comparisons, AND/OR/NOT, IN, BETWEEN,
IS [NOT] NULL, LIKE) — anything else keeps its conjunct local — and the
synthetic columns (__mo_query, __mo_filepath, the error-mode columns) are
masked out of it so a predicate on one can never reach the remote.

It is opt-in via 'recheck' = 'false', the same knob and the same reason as
DATASTREAM: a pushed predicate is not provably superset-preserving across
engines, so the remote may drop a row MO would have kept under a different
collation, time zone or coercion, and no local recheck can bring it back.
Wrapping adds a second requirement — the text must be a wrappable SELECT
that exposes the DECLARED column names, since result mapping is positional
and only the WHERE clause needs names. A source failure on a wrapped query
now says so, instead of leaving the user with a bare "column id does not
exist". ESQL rejects the option rather than accepting a no-op knob.

Defaults are unchanged everywhere: the option defaults to true, an envelope
written before pushdown existed decodes as true (never as the bool zero
value), the plan field is the positive form so its zero value is "verbatim",
and SHOW CREATE renders "recheck" only when a table opted in.

Verified end to end against a loopback SQL external table: the remote's own
statement log shows it received the wrapper, and answers match the
non-pushdown table row for row.
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

The first cut filtered on MO's DECLARED column names, which is wrong. A
foreign scan maps the result positionally -- field i feeds declared column i,
the source's names are never read -- so

    create external table t (id bigint, name varchar(64)) engine = sql ...
    select * from t where __mo_query = 'select a_id, a_name from src'

is legal, and the source has no column called `id` at all. Pushing
`where `id` > 3` at it turned a working query into "Unknown column 'id'".
Requiring the text to project the declared names, as the first cut did, gives
that freedom away for a table that never asked for it.

So MO no longer guesses: it asks the source. Before sending a filtered query
the reader probes the wrapped-but-unfiltered text --

    select * from (<text>) `__mo_subq_<hash>` limit 0

-- takes the result's column names, pairs them with the declared columns BY
POSITION (the correspondence the scan already relies on), and renders the
predicate in the source's own vocabulary: `where (`a_id` > 3)`. LIMIT 0 keeps
it a metadata round trip, and it doubles as the check that the text can be a
derived table at all, so a SHOW or a duplicate-named projection fails there
rather than on the real query. The probe is skipped when nothing was
renderable anyway, so a scan that cannot benefit pays nothing.

This moves rendering from compile to the reader, since only the reader holds a
connection. Compile now only OFFERS conjuncts (ForeignScan.pushdown_filters),
keeping those over declared columns -- a synthetic column has no counterpart at
the source -- and it no longer removes them from FilterList. MO evaluates them
regardless, which makes every fallback safe: no prober on the connection (any
non-MySQL driver, since MO renders MySQL-quoted identifiers and PostgreSQL
could not parse them -- a second bug in the first cut), an unprobeable query,
an arity mismatch, or nothing renderable all end in the verbatim query and a
correct answer, merely unoptimized.

The option is therefore 'pushdown' = 'true' (default false), not
'recheck' = 'false': MO always re-applies the predicate locally now, so
DATASTREAM's recheck semantics would be a misnomer. The opt-in remains,
for the reason DATASTREAM has it: a pushed predicate is not provably
superset-preserving across engines, and a row the source drops cannot be
recovered locally.

Measured on a 100-row source through a table declared (id, name) over columns
named (a_id, a_name): EXPLAIN ANALYZE shows the external scan taking
inputRows=1 (84 bytes) with pushdown against inputRows=100 (8.20 KiB) without,
for the same answer.
@fengttt

fengttt commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

Correction pushed (54baad7): the pushed predicate now uses the SOURCE's column names

The first cut filtered on MO's declared names, which is wrong. A foreign scan maps the result positionally — field i feeds declared column i, the source's names are never read — so this is legal:

create external table t (id bigint, name varchar(64)) engine = sql ...;
select * from t where __mo_query = 'select a_id, a_name from src' and id > 3;

The source has no column called id at all. Sending it where \id` > 3turned a working query intoUnknown column 'id'`, and requiring the text to project the declared names — what the first cut documented — gives away a freedom the positional contract grants, for a table that never asked.

MO no longer guesses; it asks the source. Before sending a filtered query the reader probes the wrapped-but-unfiltered text:

select * from (
select a_id, a_name from src
) `__mo_subq_1a2b3c4d` limit 0

reads the result's column names, pairs them with the declared columns by position — the correspondence the scan already relies on — and renders the predicate in the source's own vocabulary: where (`a_id` > 3). LIMIT 0 keeps it a metadata round trip, and it doubles as the check that the text can be a derived table at all, so a SHOW, a CALL or a duplicate-named projection fails there rather than on the real query. The probe is skipped entirely when nothing was renderable anyway.

Consequences

  • Rendering moved from compile to the reader, since only the reader holds a connection. Compile now only offers conjuncts (ForeignScan.pushdown_filters), keeping those over declared columns, and no longer removes them from FilterList.
  • Every fallback is therefore safe. No prober on the connection, an unprobeable query, an arity mismatch, or nothing renderable all end in the verbatim query and a correct answer, merely unoptimized.
  • Second bug fixed by the same change: the first cut rendered MySQL-quoted identifiers at any driver, including PostgreSQL, which sql_tvf fully supports. Only MySQL connections implement PushdownProber, so a PostgreSQL source now falls back instead of being sent SQL it cannot parse.
  • The option is now 'pushdown' = 'true' (default false), not 'recheck' = 'false'. MO always re-applies the predicate locally now, so DATASTREAM's recheck semantics would be a misnomer. The opt-in itself stays, for DATASTREAM's reason: a pushed predicate is not provably superset-preserving across engines, and a row the source drops cannot be recovered locally.

Measured

100-row source, table declared (id, name) over source columns (a_id, a_name), same answer both ways:

external scan input
pushdown = true inputRows=1, 84 bytes
default inputRows=100, 8.20 KiB

New tests cover the name substitution itself and each fallback (no prober, probe failure, arity mismatch, unrenderable conjunct, not opted in), plus that no round trip is spent when nothing could be pushed. BVT gains the renaming cases, including a projection of computed expressions (select id+100 as ident, upper(name) as nm ...) where no declared name exists at the source at all.

@aptend aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Requesting changes for a reproducible portable-identifier correctness hole at exact head 4d2259732a37e7ca72aab4c41d0c7bbaabeec039. The new bare-identifier path removes a rendered conjunct from local evaluation, so its reserved-word decision must be conservative for every supported source. The current list is incomplete even for its stated MySQL 8.0 target: _FILENAME is reserved, but is accepted and emitted bare. A valid foreign query that exposes a quoted _filename column therefore becomes an invalid wrapper instead of leaving the predicate local. I reproduced this by adding _filename to the existing reserved-word table in TestDeparseFiltersBareIdents; the test fails with actual output (_filename > 3). The normal focused packages pass on the submitted code, as do vet and focused race repetitions; this counterexample is the blocker.

Comment thread pkg/sql/datastream/filter.go Resolved

@aunjgr aunjgr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Requesting changes on exact head .\n\nThe bare-identifier allowlist is not conservative enough for a path that removes the rendered conjunct from local evaluation. Its handwritten reserved-word set is incomplete even for the stated MySQL 8.0 target: is reserved but accepts it. A valid source column referenced as quoted is therefore emitted as bare ; the remote wrapper fails instead of leaving that predicate local.\n\nPlease derive the decision from an authoritative complete portability policy (or fail closed for names not proven portable), and add reserved-identifier regressions including .

@aunjgr aunjgr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Requesting changes on exact head 4d2259732a37e7ca72aab4c41d0c7bbaabeec039.

The bare-identifier allowlist is not conservative enough for a path that removes the rendered conjunct from local evaluation. Its handwritten reserved-word set is incomplete even for the stated MySQL 8.0 target: _FILENAME is reserved but isBareIdentifier accepts it. A valid source column referenced as quoted _filename is therefore emitted as bare (_filename > 3); the remote wrapper fails instead of leaving that predicate local.

Please derive the decision from an authoritative complete portability policy (or fail closed for names not proven portable), and add reserved-identifier regressions including _FILENAME.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Deep re-reviewed exact head 4d2259732a37e7ca72aab4c41d0c7bbaabeec039 against base b0ae66c04d9a67175d2dfb8bf1c777fb888e1430.

The current revision closes most of my prior findings: the public option/body/docs now agree on pushdown=true; rendered conjuncts leave local FilterList while unrenderable ones remain; default/legacy envelopes and the plan zero value stay verbatim; source column names are checked before rows are consumed; and the PostgreSQL quoted-uppercase limitation is explicitly documented. Stream ownership is also sound: a failed name check closes/cancels the pipe and remote rows, and ordinary Close retains only the session-owned DB connection. The opted-in hot path adds no probe round trip and can materially reduce transferred rows.

One correctness/design blocker remains at the core decision boundary. reservedIdents claims to be the MySQL 8.0/PostgreSQL reserved-word union, but the handwritten set is incomplete: MySQL reserves _FILENAME, while isBareIdentifier("_filename") returns true. The compiler therefore emits (_filename > 3), removes that conjunct from node.FilterList, and sends a wrapper that MySQL rejects, although the original quoted source query plus local filtering was valid. This is a public-path behavior regression, not a missed optimization.

Please replace the manually asserted portable set with a complete, traceable policy for the supported source versions, or use dialect-aware identifier quoting/selection at the runtime boundary where the SQL driver is known. Pin _filename and the policy's source/version in tests. Merely adding this one token would leave the same maintenance and proof gap for the next source release.

The revision-3 document is now coherent enough to serve as the candidate design, but its key “safe bare identifier” invariant is disproved by this counterexample and it still has no independent approval of a corrected exact revision. Once the portability rule is made authoritative and that revision is approved, the remaining implementation shape is reviewable. Exact-head CI and git diff --check are green; they do not cover this counterexample or a PostgreSQL public path.

Review found `_FILENAME` missing from a set the comment called the union of
MySQL 8.0 and PostgreSQL reserved words. It was right, and the failure mode is
the one this set exists to prevent: a reserved word that is absent gets
rendered bare, the conjunct leaves FilterList, and the source rejects a query
that now has no local path to fall back to.

Re-derived the set from the published keyword lists rather than patching the
one word. Four were missing: _filename, x509, slow (MySQL 8.0) and any
(PostgreSQL). The URLs are now recorded beside the set so it can be checked
again, and the comment says which way it must err -- long, never short: a
spurious entry costs one conjunct its pushdown, a missing one costs the whole
query.

TestReservedIdentsIsTranscribedNotGuessed pins a sample chosen for exactly
this failure: the MySQL entries a hand-written set tends to miss because they
do not look like keywords (_filename, x509, slow, io_after_gtids,
master_ssl_verify_server_cert, zerofill), the PostgreSQL-only ones (any,
variadic, ilike, freeze, concurrently, isnull, placing, tablesample), and the
ordinary column names that must NOT be in it or pushdown would rarely fire.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Deep re-reviewed exact head 28a16aa3c85bef86a7cf9a546f32a7c3385f8ac4 against merge base b0ae66c04d9a67175d2dfb8bf1c777fb888e1430, including the full DDL -> envelope/plan -> compile/filter removal -> remote SQL -> result-name check/stream cleanup path and the delta from my prior reviewed head 4d2259732a37e7ca72aab4c41d0c7bbaabeec039.

The _FILENAME counterexample is fixed, and the current contract is much clearer. Safe defaults/legacy envelopes remain verbatim, pushed and residual conjuncts are separated correctly, the name-mismatch path closes/cancels the stream, ordinary close keeps only the session-owned connection, and no probe round trip was reintroduced. A selective pushed predicate can materially reduce remote transfer.

Three approval blockers remain.

[P1 correctness] The claimed portable reserved-word set is still incomplete

I independently extracted the PostgreSQL column from the exact official PostgreSQL 16 table linked at pkg/sql/datastream/filter.go:295 and compared every entry whose status starts with reserved against reservedIdents. The code still omits system_user; PostgreSQL 16, 17, and 18 all classify SYSTEM_USER as reserved. Consequently isBareIdentifier("system_user") returns true, DeparseFiltersBareIdents emits it bare, and compileForeignScan removes that conjunct from local FilterList. A PostgreSQL foreign query exposing ... AS "system_user" can work on the verbatim/local path, but pushdown=true plus WHERE system_user > 3 produces a remote parse failure with no local fallback.

There is also a version-contract hole: sql_tvf accepts generic mysql connections and performs no server-version gate, while the list is pinned only to MySQL 8.0. MySQL 8.4 marks QUALIFY reserved, and it is absent here. Either explicitly validate/restrict supported server versions or make the policy cover the versions the connector actually accepts.

The new spot-check test cannot prove completeness; this second omission immediately demonstrates that hand transcription plus samples is not an authoritative safety boundary. Please generate a checked-in set from pinned source data with a reproducible exhaustive verifier, or move dialect/version-aware identifier selection/quoting to the runtime boundary. Add system_user and the supported-version cases to the public contract/tests, but do not fix this by adding only the newly found tokens.

[P1 performance / Q3] Compile can amplify O(N + M) input into O(N * M) retained memory

DeriveForeignQueryList has no candidate-count/byte bound. compileForeignScan builds one filter string and then WrapPushdownQuery materializes a complete copy of it into every entry of queryList (pkg/sql/compile/compile.go:2717-2722). Thus N candidate queries and an M-byte pushed literal/filter retain Θ(N*M) bytes before execution. A compact valid shape such as 10,000 short, distinct __mo_query IN (...) candidates plus one 100 KiB printable string predicate is only hundreds of KiB on input but creates roughly 1 GiB of wrapped query strings on the CN before the first remote query runs.

Keep the common pushed filter separate and wrap one query lazily as it is opened, and/or enforce explicit candidate-count and aggregate generated-byte limits with a deterministic error. The current eager cross-product is an avoidable CN OOM path; the fact that queries later execute sequentially does not bound compile memory.

[P1 design gate] The final cross-component design still has no independent exact-revision approval

docs/cn/esql_sql_exttab.md now self-labels revision 3 as settled, but no independent reviewer has approved that exact design revision. This feature changes a public DDL option, catalog envelope, plan wire shape, compile semantics, execution ownership, and SQL sent across a MySQL/PostgreSQL trust boundary; my prior review explicitly required a traceable independent design decision. Updating the implementation document in the same author branch does not satisfy that gate. Obtain and record an independent PASS/REQUEST_CHANGES decision on the corrected exact revision.

Q1 cleanup is otherwise closed (stream/rows/context single-release); Q2 adds no unbounded wait beyond the existing context-cancelled foreign query; Q3 is blocked by the eager N*M materialization above. Exact-head CI and git diff --check are green. Local focused binaries could not start because this checkout's shared thirdparties/install lacks libmo.dylib; that environment issue does not affect the source-list comparison or the compile-time growth proof.

This branch was previously deployed

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

Labels

size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants