Repository navigation
feat: esql_tvf / sql_tvf table functions and ENGINE = ESQL|SQL foreign external tables - #27489
Conversation
Query-time foreign data integration as table functions: select * from esql_tvf(esql, schema, conn) t -- Elasticsearch ES|QL select * from sql_tvf(sql, schema, conn) t -- foreign SQL via database/sql plus session-scoped connection management builtins esql_tvf_connect / esql_tvf_disconnect / sql_tvf_connect / sql_tvf_disconnect. Design: - The schema argument reuses the parse_jsonl_data column spec (short and long JSON forms; helper extracted to tvf_schema.go) and is resolved at plan time from a constant literal. Omitted/NULL schema returns one JSON column whose rows are arrays of the source's string fields. The declared schema fixes CSV field positions; output columns are mapped back by name, so optimizer column pruning cannot misalign fields. - Both TVFs stream results through the existing external CSV reader (newCSVParserFromReader + makeBatchRows), so type coercion and NULL handling are identical to CSV external tables. ES|QL responds CSV natively (RFC 4180, header skipped, empty numeric = NULL); sql_tvf encodes *sql.Rows into the MySQL CSV dialect (\N NULL sentinel, backslash escaping) with a round-trip unit test against the real parser. - Connections are cached on the interactive frontend Session (new optional process.ForeignConnCache capability + process.ForeignConn), keyed by a config-derived handle so reconnecting with the same config reuses the connection. All connections close in Session.Close. conn NULL/omitted falls back to @esql_tvf_config / @sql_tvf_config. - Source TVFs compile single-instance on the session CN (TblFunc.IsSingle); separate TVF calls in one query still run as parallel scopes. - sql_tvf drivers: mysql and postgres (pgx); the driver registry keeps Oracle / SQL Server as a follow-up. New deps: go-elasticsearch/v8, pgx/v5 (direct). - The ES client gets an explicit http.Transport because MO's fileservice replaces http.DefaultTransport with a RoundTripper the client cannot clone. Tests: - BVT test/distributed/cases/function/tvf_sql.sql runs sql_tvf against the MO server itself over loopback (verified 19/19 live). - esql_tvf E2E mirrors the mongodb harness: optools/esql_ci.bash stands up a single-node Elasticsearch 8.15 in docker, seeds it, runs the Go driver in test/esqltvf/, and tears down (verified: all 8 cases pass live). Manual workflow .github/workflows/esql-tvf.yml; make test-esql-tvf-e2e-local. - Unit tests cover the schema helper, plan binder, CSV encoder round-trip, both reader dialects, pruning, the operator, builtins, and session cache. Known limitation: connect() config strings (incl. DSN credentials) appear in statement logs; secret references (env:) are a follow-up, as in datastream. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The external-table twins of esql_tvf / sql_tvf (docs/cn/esql_sql_exttab.md):
CREATE EXTERNAL TABLE t (col ...) ENGINE = ESQL|SQL
[WITH ('config' = '<json or env:NAME>' [, 'query' = '<text>'])]
The column list is the schema; the connection comes from the 'config' option
(inline JSON, an env:NAME reference resolved on the CN at scan time, or the
session's @esql_tvf_config / @sql_tvf_config); the foreign query text is a
pushed-down predicate on the hidden column __mo_query.
__mo_query mirrors __mo_filepath with the query text in the file-name role:
- candidates are derived at compile time from `__mo_query = <expr>`,
`IN (...)`, and OR combinations (external.DeriveForeignQueryList), where
<expr> follows the same compile-time-safety rules as file-level filters
(literals, prepare params, session vars, foldable functions);
- the unchanged external.FilterFileList then applies every query-level
conjunct (non-generating ones like LIKE prune the list) and leaves only
row-level conjuncts for MO to evaluate locally — there is no deparser, no
recheck option: pushing predicates into the foreign text is the user's job;
- each returned row carries the text that produced it, so IN (...) plus a
projected __mo_query tells which query yielded which row;
- with no derived candidate the 'query' table option is the default, else the
scan errors. PREPARE works: __mo_query = ? derives at EXECUTE.
Wiring mirrors ENGINE = DATASTREAM: tree.ForeignTableParam (Format redacts an
inline config; env: refs stay verbatim), MO_FOREIGN rel_createsql envelope in
new client-free pkg/sql/foreignext, durable features.ForeignExternal bit that
must agree with the envelope, plan.ForeignScan (ExternType FOREIGN_TB), SHOW
CREATE with redacted config that re-parses, statement-log redaction, INSERT
rejected. Grammar adds ESQL as a non-reserved keyword and reuses the SQL
token; zero parser conflicts; `ENGINE = SQL` in ordinary CREATE TABLE still
parses as a plain table option.
Execution reuses the whole foreigntvf + external CSV stack: the scan is
ScanType INFILE so the operator's file loop iterates the derived query texts,
ForeignScanReader resolves the session-cached connection per text (an external
table and a TVF with the same config share one connection) and streams the
CSV result (ES|QL format=csv / sql.Rows encoder) through the shared reader.
One scope on the session CN, Mcpu=1; foreign queries within a scan run
sequentially, separate scans in one query run concurrently.
Tests:
- BVT test/distributed/cases/function/foreign_exttab.sql: loopback ENGINE=SQL
against MO itself — derivation shapes, local predicates, __mo_query
projection, 'query' default, session-var config, prepare, ETL
INSERT...SELECT, SHOW CREATE redaction, hidden-column invisibility, and all
error cases (verified 34/34 live).
- E2E: 6 new ENGINE=ESQL cases over the seeded index incl. env: config
(MO_ESQL_E2E_CFG exported into mo-service) and IN of two ES|QL queries
(verified 14/14 against a real Elasticsearch 8.15).
- Go unit: envelope round-trip (hostile ;/*/ values), option validation,
query-list derivation (=/IN/OR/NULL/negative shapes), generalized
classifier, parser round-trip with redaction.
- Regressions: tvf_sql 19/19, tvf_parse_jsonl 18/18; plan/external/parsers
package suites green (TestBuildCreateOrReplaceViewRejectsRecursiveDefinition
/future_AS_OF_timestamp fails identically at the clean upstream/main
baseline 6ff9be9 — pre-existing).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Closes the untested inline-config x ESQL combination: creates an external table with an inline 'config' JSON (credentials included), asserts a schema-typed __mo_query scan returns the seeded rows, and asserts SHOW CREATE redacts the config. Verified live: 15/15 E2E cases pass against Elasticsearch 8.15. Co-Authored-By: Claude Opus 4.8 <[email protected]>
An 'env:NAME' config argument is resolved from the CN process environment in
ResolveOrConnect, BEFORE handle hashing — so the handle is derived from the
resolved JSON and a TVF connecting via env: shares one cached connection with
an external table whose 'config' option resolved to the same JSON.
This closes the statement-log gap: connect('{...password...}') logged the
credential-bearing SQL text verbatim; connect('env:NAME') keeps every secret
out of SQL text, statement logs, query history, and session variables — the
same convention the ESQL/SQL external tables and the datastream apikey use.
Inline configs still work and still log verbatim, by user choice.
Unit tests cover resolution order, unset/empty references, and the
shared-handle property; the E2E gains a tvf-env-config case (connect via
env:MO_ESQL_E2E_CFG against a live Elasticsearch) — 16/16 cases pass.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
Self-review: error handling + data-type coverageMethodology: multi-angle sweep of the full diff (error paths, Q1 leak / Q2 hang / Q3 growth), plus live probing of data types and unhappy paths against a fresh single-node build (SQL kind over loopback; ESQL kind against a real Elasticsearch 8.15 container). Findings ranked; each was verified in code, and the top ones reproduced live. Confirmed defects (fix before merge)R1. Panic on legal SQL: self-referential select * from ft where __mo_query = __mo_query;→ R2. ALTER TABLE on a foreign table is not blocked (MongoDB has a guard; foreign — and datastream — do not). Reproduced: alter table ft2 add column x int;
-- ERROR: sql_tvf: invalid config: invalid character '<' looking for beginning of valueThe copy-based ALTER recreates the table from SHOW CREATE output, whose inline config is R3. Get-or-connect is not atomic. Two scans sharing one config in a single query (parallel scopes; the BVT even joins two R4. A truncated ES HTTP response returns a silent partial result. Data-type findings (live-probed; none of this is in the committed tests)R5. Meanwhile Verified-good (exact round-trips, live):
Documented semantics worth restating in user docs: ES CSV cannot distinguish NULL from Test-coverage gaps to close
Plus: duplicate column names in a schema spec silently alias to one field (add a dedup error); Proposed order
🤖 Generated with Claude Code |
CI: register function ids 571-574 in predefinedFunids (Test_funids) — the root cause of all three failing checks. Review fixes (see the self-review comment on matrixorigin#27489): - R1 panic: a self-referential query-level predicate (__mo_query = __mo_query, concat(__mo_query,...), IN lists containing the column) was evaluated on the zero-vector const-fold batch -> index out of range. Candidate sides must now be column-free; such conjuncts generate nothing and still prune correctly in FilterFileList. Regression tests + verified live. - R2 ALTER TABLE on ESQL/SQL (and datastream) external tables is now cleanly rejected like MongoDB; the copy path would recreate from SHOW CREATE output whose config is redacted. A replayed '<redacted>' config now errors with an explanation instead of a JSON parse failure. - R3 connect race: PutForeignConn is first-wins under the session lock and returns the cached winner; the cache never closes a connection another operator may be using — the losing connector closes its own. Interface, session impl, and all fakes updated. - R4 silent truncation: a transport-level io.ErrUnexpectedEOF from the ES response body (node restart, LB idle timeout) was indistinguishable from the CSV parser's normal final-partial-block signal -> N rows returned as success. A truncationGuard reader now remaps it to a hard error. - R5 ES ISO 8601 timestamps: ENGINE=ESQL scans with declared temporal columns rejected ES's native "...T...Z" format under strict mode (the TVF path's non-strict normalization accepted it — a spec deviation from doc §3). Foreign ESQL scans now trim the trailing 'Z' for temporal columns; verified against a live ES incl. millisecond precision and typed predicates. - Hardening: mid-stream sql driver errors are wrapped with sql_tvf attribution; ES error bodies are read through a LimitReader; EsqlConn.Close releases its private transport's idle sockets; duplicate schema-spec column names are rejected (they silently aliased two outputs to one field); non-string @*_tvf_config values get a typed error. Type-matrix tests (review asked: json/timestamp/binary/etc coverage): - BVT foreign_exttab: bool/float32/float64/decimal(18,4)/date/datetime(3)/ timestamp(3)/json (embedded commas)/varbinary (incl. NUL bytes)/unicode+ newline text, with a NULL-safe-equality join proving 0 mismatches vs the source (42/42 live). - BVT tvf_sql: the full schema-spec vocabulary (bool/int32/float32/float64/ timestamp/string) via long and short specs + duplicate-name rejection (25/25 live). - E2E: seeded a 'hired' date field; new exttab-iso8601-timestamp case parses native Z-suffixed dates into timestamp(3) with millis and typed predicates (17/17 vs live Elasticsearch 8.15). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Review findings resolved (commit 8dc02a0)CI: all three failing checks shared one root cause —
Type-matrix coverage added (was the review's biggest gap):
Full validation: unit suites green (incl. 🤖 Generated with Claude Code |
The Utils CI coverage gate measured 53.05% on the PR diff: the heavy execution-path files were exercised mainly by the loopback BVT and the manual ES E2E, which do not feed the UT coverage profile enough. Add unit suites that drive those paths in-process: - pkg/sql/foreigntvf: an httptest fake Elasticsearch (product-check handshake + ES|QL _query) covers connectESQL/Query/Close, the error-status path, and reproduces the truncated-response guard with a short Content-Length; an in-process database/sql fake driver covers connectSQL/SqlConn.Query/ encodeRowsCSV end-to-end (quote/comma escaping, \N NULL, mid-stream error attribution, early reader close), plus ResolveOrConnect/ByHandle cycles, ConfigFromSessionVar (resolver missing/unset/non-string/string/[]byte), and ValidateConfig for both kinds. Package coverage: 90.4%. - pkg/sql/colexec/external: ForeignScanReader lifecycle tests (Open resolves the session conn and sends Fileparam.Filepath; typed ReadBatch; idempotent Close; per-Open ESQL header-skip re-arm) and the Open error paths; dialect pins for ForeignExternParam. - pkg/sql/compile: TestCompileForeignScan on the NewMockCompile harness (mirrors the datastream compile test): derivation consumes the generating conjunct, 'query' option default, no-source error, missing metadata, and row-level filter retention. - pkg/sql/plan: direct tests for the SHOW CREATE formatter (redaction/env:/ optionless), IsForeignTableDef forgery cross-checks, and binder tests for the refactored parse_jsonl schema dispatch. - test/esqltvf: unit tests for the driver's pure helpers (sqlEscape, report writing, ES config JSON shape). Co-Authored-By: Claude Opus 4.8 <[email protected]>
# Conflicts: # pkg/sql/plan/function/function_id.go # pkg/sql/plan/function/function_id_test.go
aptend
left a comment
There was a problem hiding this comment.
Deep re-review completed on exact head 2ce24df9f0e86dfa48f5d50c5aac358b7fee5af0. I read the complete historical reviews, inline comments/replies, conversation, and resolved/unresolved thread state; compared the increment after my prior reviewed head 9ff7f7f81a1ccc920a46efceb07c32a6117a5147; and audited the complete diff against base 6ff9be9646a6ac43e05ba3063de27b2248bbac62. The seven findings from my prior round are now substantively closed, and after the head advanced during this review I independently verified the terminal cache-close and byte-bounded raw-batch fixes on the new exact head. One session-migration correctness blocker remains, described inline. Focused and complete affected-package tests pass; focused race loops pass at count 20; go vet passes. The full-range diff check also reports trailing whitespace in the new docs/result fixture.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 69 out of 74 changed files in this pull request and generated 2 comments.
Suppressed comments (3)
Previously missed (2) — in code that hasn't changed since the last review.
pkg/sql/foreigntvf/esql.go:62
Connectaccepts{}even thoughValidateConfigrejects it. With no addresses or CloudID, go-elasticsearch falls back to its environment/default localhost endpoint, so TVF/session-variable configs bypass the validation contract and may connect to an unintended service. Apply the same endpoint check on the connect path.
docs/cn/esql_tvf_plan.md:60- This cache design no longer matches the implementation: there is no second hash map and no new methods on
process.Session; interactive sessions implement the optional, boundedprocess.ForeignConnCacheinterface. Keeping the implementation plan synchronized avoids directing future maintenance toward nonexistent APIs.
This issue also appears on line 112 of the same file.
- `foreignConns map[string]process.ForeignConn` (handle → connection),
- `foreignConnByHash map[string]string` (config hash → handle, for reuse),
- mutex.
Expose through NEW methods on the minimal `process.Session` interface (implemented by
`*frontend.Session`, reached from colexec via `proc.GetSession()`):
docs/cn/esql_tvf_plan.md:116
- The implementation did not add Oracle or SQL Server drivers, and the cache is exposed through an optional interface rather than four
process.Sessionmethods. Update this inventory to match the shipped files/dependencies; otherwise the included plan contradicts both the code and the PR scope.
- `pkg/frontend/session.go` — cache fields, interface-method impls, `Close()` CloseAll.
- `pkg/vm/process/types.go` — `ForeignConn` interface + 4 methods on `Session` interface.
- `go.mod` — add `github.com/elastic/go-elasticsearch/v8`; promote `jackc/pgx/v5` to direct;
add `github.com/sijms/go-ora/v2` (Oracle, pure Go) + `github.com/microsoft/go-mssqldb`
(SQL Server, pure Go). MySQL + Mongo already present.
Review round 4 (aptend + Copilot): - [P1] Connection migration fails closed while the session caches any foreign connection: migrateConnectionFromActionWithContext returns OkExpectedNotSafeToStartTransfer (the pending-long-data precedent), since neither the pools/transports nor the handle map migrate and a transferred client would keep handle strings that resolve to nothing on the target CN. Disconnecting the handles unblocks the transfer. Regression mirrors the reviewer's shape: seeded cache -> not-safe; removed -> migrates. - [security] 'env:NAME' config references now require the sys account on BOTH resolution paths (TVF connect and foreign-table scans): the CN process environment is operator-owned and shared across tenants, so a tenant guessing an operator-defined name must not be able to use its credentials. Non-sys and account-less contexts get a clear error; unit regressions added for both paths (the E2E runs as sys and still passes 20/20 against live Elasticsearch). - [P2] fixed the remaining 'esql_connect' reference in docs/cn/esql_tvf.md and stripped trailing whitespace from the feature docs. Co-Authored-By: Claude Opus 4.8 <[email protected]>
iamlinjunhong
left a comment
There was a problem hiding this comment.
Reviewed exact head 4ab6d9ddfedadfb30113b33c447b893ba3eb233b against merge-base 19546540446ad30488c1a8f4d7a45a8db3723cee and fresh origin/main a4465b3846c770b8f3e2c313a624afd8534427da. I inspected the complete diff and the relevant planner/compile/operator/session/driver call chains, and read the previous review, all review threads, and the PR conversation. The author explicitly replied to the previous round's P2, and the two previous P1s plus that P2 are fixed on this head.
Blocking findings:
-
[P1/security] Enforce the ESQL endpoint check on the actual connect path.
pkg/sql/foreigntvf/esql.go:58-90unmarshals the config and callselasticsearch.NewClientwithout theaddresses/cloudidcheck invalidateESQLConfig(:45-53). That validator is only called for inline foreign-table DDL;esql_tvf_connect, the session-variable fallback, and scan-time configs all reachconnectESQLdirectly throughResolveOrConnect. In go-elasticsearch v8.15, an empty config readsELASTICSEARCH_URLand otherwise defaults tohttp://localhost:9200(including URL userinfo as client credentials). Therefore a non-sys tenant can callesql_tvf_connect('{}')and bypass the new sys-onlyenv:gate, potentially obtaining the operator-configured Elasticsearch target/credentials. Validate the endpoint insideconnectESQL(or have every runtime path call the same validator) beforeNewClient, and add a regression that proves{}cannot inherit process defaults. -
[P1/Q2] Keep the session-pinned foreign scan in the distributed shuffle receiver graph.
pkg/sql/compile/compile.go:2636creates every foreign external scan withconstructScopeForExternal(c.addr, false), so the source must stay on the interactive session CN. ButshuffleJoinStageNodesonly adds an off-worker local dependency forSINK_SCAN, andattachShuffleDispatchSourceattaches a source only when a receiver has the same execution node unless that special fallback is enabled. On an AP multi-CN plan whose scheduled query-worker set excludes the coordinator,INSERT INTO pk_dst SELECT ... FROM foreign_ft WHERE __mo_query = ...can choose the distributed DEDUP shuffle used for primary-key insertion; no receiver owns the coordinator-local foreign source, so it is never started while all shuffle receivers wait. This is the same wait-for break documented immediately below for MongoDB atcompile.go:2645-2665, except this source cannot simply move remote because its connection cache is session-local. Include the current CN in the receiver stage/dependency graph and add the corresponding multi-CN compile regression.
Non-blocking but current:
- [P2/compatibility] Preserve real
__mo_querycolumns in pre-existing schemas.pkg/catalog/types.go:115-116makesContainExternalHidenColclassify__mo_queryglobally by name. The new CREATE/ALTER rejection prevents future definitions but cannot retrofit existing tables. After upgrade, an existing ordinary table silently loses that column fromSELECT *(pkg/sql/plan/query_builder.go:6149/bind_context.go:454), and an existing generic external table can have its real field replaced with the synthetic filepath value (pkg/sql/colexec/external/external.go:1194). Scope query-column hiding/materialization toFOREIGN_TBplusExternalQueryColId, while retaining the reservation for new schemas, and cover a pre-existing-table counterexample.
The current tests cover the standalone foreign-scan scope and the validator in isolation, but not the two production paths above. Because confirmed P1 issues remain, this review requests changes.
scope __mo_query hiding by ColId
Review round 5 (iamlinjunhong):
- [P1/security] connectESQL now runs the same endpoint validation as the DDL
path before NewClient: go-elasticsearch treats an empty config as "read
ELASTICSEARCH_URL or default to localhost:9200" (URL userinfo included),
so esql_tvf_connect('{}') could inherit operator-configured process
defaults and bypass the sys-only env: gate. Regression sets
ELASTICSEARCH_URL and proves '{}' (and endpoint-less configs) fail on both
the direct and ResolveOrConnect paths.
- [P1/Q2] the session-pinned foreign scan now counts as a CN-pinned local
source in the shuffle receiver graph (same mechanism as SINK_SCAN):
operatorTreeContainsSinkScan also detects an External op with a
ForeignScan, so shuffleJoinStageNodes includes the session CN in the
receiver stage set and attachShuffleDispatchSource keeps the scope local.
Regression: with query workers excluding the session CN, the stage set
gains the session CN at Mcpu=1 and hasLocalDependency=true.
- [P2/compatibility] __mo_query hiding/materialization is scoped to the
synthetic column: ContainExternalHidenCol is filepath-only again;
IsForeignQueryCol (name + reserved ColId) drives binding hiding
(addBinding) and visible-column filtering; getFieldFromLine synthesizes
__mo_query only when ForeignScan is set; makeFilepathBatch checks the
ColId; CREATE/ALTER reservation moves to IsReservedExternalColName (both
names, unchanged behavior). Counterexamples: a pre-existing REAL
__mo_query column stays in SELECT * and is directly selectable, and a
generic external table's real __mo_query field reads source data, while
the foreign scan's synthetic column stays hidden.
Full suites, lint, race, and the E2E (20/20 vs live Elasticsearch) pass.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Review round 5 (@iamlinjunhong) — all three findings fixed (commit af78466)1. [P1/security] ES endpoint validation on the connect path. 2. [P1/Q2] Foreign scan in the shuffle receiver graph. Took your "include the current CN" direction via the existing SINK_SCAN mechanism: 3. [P2/compat] Pre-existing Validation: full unit suites + catalog/plan/compile/external/frontend green, lint 0 issues, E2E 20/20 against live Elasticsearch on the new head. CI running. 🤖 Generated with Claude Code |
The CI BVT runner executes every case file through one shared session (my local runs used one invocation per file, hiding this). foreign_conn_limit deliberately filled the 16-slot connection cache and exited without disconnecting, so every later foreign case in the same session failed with 'this session already caches 16 foreign connections' (plus one stale pooled conn surfacing as 'Unknown database foreign_exttab'). This was the COMPOSE/ PESSIMISTIC BVT failure; the Utils Coverage failure was its cascade. Every foreign BVT file now disconnects everything it connected before finishing: foreign_conn_limit captures @H1..@h17 and disconnects them all (also asserting the whitespace-variant now via handle equality), and foreign_exttab/tvf_sql end with a disconnect of their loopback config. Verified per-file AND with all three files in one mo-tester invocation emulating the CI shared session: 134/134. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…rocessing Design rule: query processing never reads the CN process environment; all connection info comes from user input or the session. Remove the env:NAME config-reference mechanism everywhere: - foreigntvf: delete resolveConfigRef (and its sys-account gate); ResolveOrConnect uses the given config verbatim. - foreignext: delete ResolveConfig; the '<redacted>' rejection now points at the session-variable form instead of env:. - ForeignScanReader: config = inline table option, else session variable. - datastream: delete ResolveAPIKey; the apikey option is used literally. - tree/SHOW CREATE: every config value is redacted (no env: carve-out). - build_ddl: every non-empty inline config is shape-validated. - E2E: env: cases replaced with inline-config cases; the cross-kind case now opens a REAL loopback sql connection so it proves the kind check itself (previously it passed on an unrelated connect error), with HTML-escaping off for the DSN's '&'; harness no longer exports MO_ESQL_E2E_CFG. os.Getenv remains only in test fixtures (t.Setenv guarding the ES client's env-reading behavior) and non-query-processing paths. Validated: unit suites (foreigntvf/foreignext/datastream/external/parsers/ plan/compile/frontend) green, golangci-lint clean, ES E2E 20/20, combined foreign BVT 134/134 on a fresh build. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Design change in 2b916c7: the `env:NAME` config-reference mechanism is removed entirely. Rule adopted: query processing never calls `os.Getenv` — all connection info comes from user input or the session. An env-resolved config made query results depend on per-CN process state (invisible to the user, non-deterministic across CNs, and a tenant-isolation hazard that previously needed a sys-account gate to paper over). What changed:
This supersedes the earlier review replies about tenant-scoping/gating of `env:` references — those code paths no longer exist. `os.Getenv` remains only in test fixtures (e.g. `t.Setenv("ELASTICSEARCH_URL", ...)` proving the connect path cannot inherit process defaults). Validation: unit suites green, golangci-lint clean, ephemeral-ES E2E 20/20, combined foreign BVT 134/134 on a fresh build. |
The kind-mismatch error embeds the connection handle, whose hex is a hash of the connection config — it differs whenever the server address differs (local genrs ran against 127.0.0.1:6101, CI runs against 6001), which failed the COMPOSE(PROXY) BVT. Use mo-tester's @regex directive so the assertion is the kind-check message itself, not the config-dependent handle. Verified: 34/34 on a server whose actual hash deliberately differs from the recorded text. Co-Authored-By: Claude Fable 5 <[email protected]>
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep review of the current head (bfd7495). The earlier requested changes are largely addressed, but two blocking unhappy-path/compatibility defects remain:
-
[P1][resource lifecycle] Close the private Elasticsearch transport on every failed connect.
connectESQLcreates a freshhttp.Transport, but transfers ownership toEsqlConnonly on success. TheNewClient,Info, and non-2xx return paths leave no owner that can callCloseIdleConnections. This is observable, not theoretical: with anhttptestendpoint returning a zero-length 401, 8 failedconnectESQLcalls left 8 distinct server connections inStateIdle. Each private pool can retain its socket forIdleConnTimeout(90s); failed connects are never admitted to the 16-entry session cache, so retries can accumulate sockets/goroutines without that bound and cause FD/memory pressure or availability loss. Add a failure-path ownership guard that closes the transport after the response body is closed unless ownership is transferred toEsqlConn, plus a ConnState regression test for HTTP error handshakes. -
[P1][compatibility/security] Do not silently reinterpret existing DATASTREAM
apikey=env:NAMEtables. The current base resolves this syntax at scan time viadatastream.ResolveAPIKey, errors for malformed/unset references, and has regression tests. This head deletes the resolver/tests and sendsds.ApiKeyverbatim. After upgrade, an existing table withapikey=env:DS_KEYsends the literal stringenv:DS_KEYand starts failing authentication; there is no catalog migration, feature gate, deprecation, or explicit validation error. Removing this behavior also pushes users toward inline secrets stored in catalog/plan/statement text. Restore the existing contract in this feature PR. If process-env lookup must be retired, do that as a separately coordinated migration with an explicit fail-closed error and a secure replacement secret source—never as a silent literal reinterpretation. Keep coverage for existing persisted table definitions.
Local verification: all affected unit packages passed (foreigntvf, datastream, external, table_function, plan/function, foreignext, MySQL parser, plan, compile, frontend). git diff --check also reports trailing whitespace in test/distributed/cases/function/foreign_exttab.result:29 (non-blocking).
…: apikey Review round 6 (XuPeng-SH): 1. connectESQL creates a private http.Transport but transferred ownership to EsqlConn only on success: the NewClient-error, Info-error, and non-2xx paths left keep-alive sockets idle for IdleConnTimeout with no owner, and failed connects are never admitted to the bounded session cache, so retries accumulated sockets without bound. An ownership-flag defer now drains the transport on every failure path (after the response body is closed). Regression: ConnState-tracking test proves 8 failed handshakes leave 0 open server connections (failed pre-fix with 8). 2. A pre-existing DATASTREAM table whose persisted definition carries the retired "env:NAME" apikey syntax no longer silently sends the literal string as the credential: both ParseTableOptions (new DDL) and the scan path (persisted defs) fail closed with an explicit "no longer supported" error telling the user to recreate the table with the apikey value. Query processing still never reads the CN process environment. The flagged trailing whitespace in foreign_exttab.result:29 is load-bearing: it is the empty Comment cell of the last DESC row, and mo-tester compares cell-by-cell (verified: stripping it fails the case). Co-Authored-By: Claude Fable 5 <[email protected]>
… feat-esql-sql-tvf
|
@XuPeng-SH Both P1s are fixed in 5cf7cea (pushed on top of the branch-update merge, head a150ef4):
On the trailing whitespace in @iamlinjunhong Your review examined head 4ab6d9d; all three findings were fixed in the subsequent commits already on the branch before this round: (1) |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep re-review of exact head a150ef4c. The two blockers from my previous round are closed on their intended basic paths: the ordinary failed-handshake transport is drained, and the recorded project decision to retire DATASTREAM env:NAME now fails closed for both new and persisted definitions. The complete elasticsearch.Config lifecycle exposes three new blocking counterexamples, however:
-
[P1][correctness/Q1]
CACertis a reachable panic and also breaks transport ownership.connectESQLinstalls a privatehttp.TransportwhoseTLSClientConfigis nil, then passes a user-decodedCACertthroughelasticsearch.NewClient.elastictransport.Newclones that transport and dereferenceshttpTransport.TLSClientConfig.RootCAs; a valid PEM CA config reproduced an immediate nil-pointer panic instead of a SQL error. Merely initializingTLSClientConfigis insufficient: the library clone becomes the transport that owns sockets, whileEsqlConn.transportand the new failure defer still retain/close the original object. Apply CA material to the MO-owned transport before construction and clear the upstream field, retain the actual transport used by the client, or reject this option fail-closed. Add valid-CA success and 401/error regressions that assert the actual server connection closes. -
[P1][Q1-Q3] Periodic node discovery survives both failed connect and
EsqlConn.Close. A non-zeroDiscoverNodesIntervalmakeselastictransport.Newinstall a self-reschedulingtime.AfterFuncbeforeInfo. The upstream client exposes no Close/Stop method;CloseIdleConnectionsdoes not stop that timer, andDiscoverNodessends an independent request without the caller context. With a 20ms interval and an Info endpoint returning 401, I observed a later/_nodes/httprequest afterconnectESQLhad already returned and drained its transport. The callback then re-arms forever and can reopen sockets; repeated failed connects/disconnects therefore accumulate unbounded timers/goroutines outside the 16-entry session cache. A stalled discovery endpoint is worse because each interval launches another goroutine. RejectDiscoverNodesInterval > 0andDiscoverNodesOnStartunless MO owns a cancelable, bounded discovery lifecycle, and cover no-post-return/no-post-close traffic. -
[P1][concurrency/global state] Do not allow session JSON to enable the dependency process-global debug logger.
EnableDebugLogger:truewrites the package-globalelastictransport.debugLoggerwith no synchronization and never restores it. Two simultaneousconnectESQLcalls with that legal config produce a race-detector failure atelastictransport.go:251(write/write); one tenant can also permanently enable debug behavior for every client in the CN. Reject this process-global option or isolate it from user/session configuration.
These are one design boundary: JSON from a SQL session is currently unmarshaled into the full application-level Elasticsearch config, including options whose lifecycle/global effects MO cannot own. Please validate a safe subset (and fail closed on lifecycle/global knobs) rather than patching only the currently observed socket.
Verification on this exact head: all 16 changed Go package patterns resolve; build and vet pass; the new handshake cleanup regression measured 0.03s under race, passed the adaptive 30s budget at -race -count=100, and the full foreigntvf package passed under race. Normal affected-package tests pass (including an isolated frontend rerun). The three counterexamples above respectively panic, perform post-return network work, and fail under -race.
Review round 7 (XuPeng-SH): session JSON was unmarshaled into the library's full elasticsearch.Config, reaching lifecycle/process-global knobs MO cannot own from a SQL session — CACert made elastictransport clone the transport (nil-TLSClientConfig panic, and Close kept draining the original object while the clone owned the sockets), DiscoverNodesInterval installed a self-rescheduling timer with no Stop that outlives connect failure and Close, and EnableDebugLogger wrote an unsynchronized package-global. The config is now strictly decoded (DisallowUnknownFields) into a whitelist: addresses, username, password, cloudid, apikey, servicetoken, certificatefingerprint, cacert. Every other field fails closed with a clear error on both the validate and connect paths. cacert (private-CA PEM) is applied to the MO-owned transport's TLS config and never passed to the library, so Close and the failure defer keep draining the transport the client actually uses. Regressions (fail on the pre-fix code): TestESQLConfigRejectsLifecycleKnobs, TestConnectESQLCACert (valid-CA success + drain-after-Close, 401 failure drain, no-CA rejection, bad PEM). Race-stressed -count=100/-count=50 plus a full-package -race run; real-ES E2E 20/20 on a fresh build. Co-Authored-By: Claude Fable 5 <[email protected]>
|
@XuPeng-SH All three round-7 P1s are fixed in d2d3816 by adopting exactly the design boundary you proposed: the session JSON is no longer unmarshaled into the library's full
Separately, the earlier "UT Test on Ubuntu/x86" CI failure was infrastructure — the runner's onnxruntime thirdparty download timed out ( |
The Utils CI changed-line coverage gate slipped to 74.04% (< 75%): the env: removal deleted well-covered code while the E2E driver rewrite added lines that only execute against a real Elasticsearch. A scripted database/sql driver now answers every statement of the E2E script the way the seeded MO+ES stack does (including the session time_zone state, SHOW CREATE redaction, and the cross-kind rejection error), so run()/runExternalTable() execute end-to-end as a unit test and assert the exact recorded case list. Driver-file coverage rises from ~11% to ~57% of changed lines. Co-Authored-By: Claude Fable 5 <[email protected]>
What type of PR is this?
Which issue(s) this PR fixes:
issue #27488
What this PR does / why we need it:
Query-time foreign data integration with Elasticsearch (ES|QL) and external SQL databases, per
docs/cn/esql_tvf.mdanddocs/cn/esql_sql_exttab.md(both included).1. Table functions
schemareuses theparse_jsonl_datacolumn spec (short'ssI'and long JSON forms), resolved at plan time from a constant literal; omitted/NULL schema returns one JSON column of string-arrays per row. Output columns are mapped back to declared positions by name, so optimizer column pruning never misaligns fields.connis a runtime expression — a varchar handle fromesql_tvf_connect(config)/sql_tvf_connect(config), typically carried in a session variable; NULL/omitted falls back to@esql_tvf_config/@sql_tvf_config.*_tvf_disconnect(handle)closes.process.ForeignConnCachecapability), keyed by a hash of the resolved config: reconnecting with the same config reuses the connection; everything closes inSession.Close.newCSVParserFromReader+makeBatchRows), so type coercion and NULL handling are identical to CSV external tables.sql_tvfencodessql.Rowsinto MySQL-dialect CSV (\NNULL sentinel) with a round-trip unit test against the real parser.2. Foreign external tables
__mo_query, mirroring__mo_filepathwith the query text in the file-name role: candidates derive from=/IN (...)/ORconjuncts at compile time, the unchangedFilterFileListapplies all query-level conjuncts (LIKEprunes), each row carries the text that produced it, and the'query'table option is the default.PREPARE ... __mo_query = ?works.recheck: pushing predicates into the foreign text is the user's job, in the source dialect; MO evaluates every ordinary predicate locally.ENGINE = DATASTREAM:MO_FOREIGN:rel_createsql envelope (new client-freepkg/sql/foreignext) + durablefeatures.ForeignExternalbit that must agree (anti-forgery),plan.ForeignScan/ExternType_FOREIGN_TB, INSERT rejected, DESC /SELECT *hide__mo_query.ESQLadded as a non-reserved keyword,SQLtoken reused; zero parser conflicts; ordinaryCREATE TABLE ... ENGINE = SQLstill parses as a plain table option.3. Secret handling
configmay be inline JSON,env:NAME(resolved on the CN at scan/connect time), or absent (session-var fallback).env:keeps credentials out of SQL text, statement logs, query history, and the catalog entirely — the recommended production form, same convention as the datastreamapikey.'<redacted>'), emitsenv:refs verbatim, and its output re-parses.CREATEstatement logging re-renders throughForeignTableOption.Format, which performs the same redaction.env:on the connect path resolves before handle hashing, so a TVF and an external table with the same resolved config share one cached connection.Testing
function/tvf_sql.sql(19 cases) andfunction/foreign_exttab.sql(34 cases) point the SQL kind back at the MO server itself — derivation shapes, local predicates,__mo_queryprojection, defaults, session-var config, prepare, ETLINSERT...SELECT, SHOW CREATE redaction, hidden-column invisibility, and all error paths. Verified live.make test-esql-tvf-e2e-local/.github/workflows/esql-tvf.ymlstands up a single-node Elasticsearch 8.15 in docker, seeds it, boots a fresh mo-service, runstest/esqltvf/esql_e2e_local.go, and tears down. 16/16 cases pass against the live ES: 9 TVF (incl. env: connect, ES|QL-side and MO-side filtering, null mapping, no-schema mode) + 7 external-table (incl. env: and inline config with redaction assert, IN of two ES|QL queries, session-var config).;/*/DSNs, query-list derivation (=/IN/OR/NULL/negative shapes), both CSV dialects, pruning alignment, operator, builtins, session cache (incl. concurrent under-race).tvf_parse_jsonl18/18 (its schema helper was extracted and reused); plan/external/parsers suites green (TestBuildCreateOrReplaceViewRejectsRecursiveDefinition/future_AS_OF_timestampfails identically at the clean upstream/main baseline6ff9be9646— pre-existing).New deps:
github.com/elastic/go-elasticsearch/v8(ES client),github.com/jackc/pgx/v5promoted to direct (postgres). Oracle / SQL Server stay behind the driver registry as follow-ups. Note: MO's fileservice replaceshttp.DefaultTransport, so the ES client gets an explicithttp.Transport.🤖 Generated with Claude Code