Skip to content

feat: esql_tvf / sql_tvf table functions and ENGINE = ESQL|SQL foreign external tables - #27489

Merged
fengttt merged 23 commits into
matrixorigin:mainfrom
fengttt:feat-esql-sql-tvf
Aug 24, 2026
Merged

fengttt merged 23 commits into
matrixorigin:mainfrom
fengttt:feat-esql-sql-tvf

Conversation

@fengttt

@fengttt fengttt commented Aug 22, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • FEATURE

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.md and docs/cn/esql_sql_exttab.md (both included).

1. Table functions

select * from esql_tvf(esql, schema, conn) t;   -- Elasticsearch ES|QL (format=csv)
select * from sql_tvf(sql, schema, conn) t;     -- foreign SQL via database/sql (mysql, postgres)
  • schema reuses the parse_jsonl_data column 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.
  • conn is a runtime expression — a varchar handle from esql_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.
  • Connections are cached on the interactive frontend session (new optional process.ForeignConnCache capability), keyed by a hash of the resolved config: reconnecting with the same config reuses the connection; everything closes in Session.Close.
  • Both TVFs stream results through the existing external CSV reader (newCSVParserFromReader + makeBatchRows), so type coercion and NULL handling are identical to CSV external tables. sql_tvf encodes sql.Rows into MySQL-dialect CSV (\N NULL sentinel) with a round-trip unit test against the real parser.
  • Source TVFs compile single-instance on the session CN; separate calls in one query run as parallel scopes.

2. Foreign external tables

CREATE EXTERNAL TABLE es_logs (ts timestamp, host varchar(100), status int)
ENGINE = ESQL WITH ('config' = 'env:ES_CFG');

SELECT ts, host FROM es_logs
WHERE __mo_query = 'FROM logs-* | WHERE status >= 500 | KEEP @timestamp, host, status'
  AND host LIKE 'web-%';
  • The column list is the schema; the foreign query text is a pushed-down predicate on the hidden column __mo_query, mirroring __mo_filepath with the query text in the file-name role: candidates derive from = / IN (...) / OR conjuncts at compile time, the unchanged FilterFileList applies all query-level conjuncts (LIKE prunes), each row carries the text that produced it, and the 'query' table option is the default. PREPARE ... __mo_query = ? works.
  • No deparser, no recheck: pushing predicates into the foreign text is the user's job, in the source dialect; MO evaluates every ordinary predicate locally.
  • Catalog wiring mirrors ENGINE = DATASTREAM: MO_FOREIGN: rel_createsql envelope (new client-free pkg/sql/foreignext) + durable features.ForeignExternal bit that must agree (anti-forgery), plan.ForeignScan / ExternType_FOREIGN_TB, INSERT rejected, DESC / SELECT * hide __mo_query.
  • Grammar: ESQL added as a non-reserved keyword, SQL token reused; zero parser conflicts; ordinary CREATE TABLE ... ENGINE = SQL still parses as a plain table option.

3. Secret handling

  • config may 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 datastream apikey.
  • SHOW CREATE redacts an inline config ('<redacted>'), emits env: refs verbatim, and its output re-parses. CREATE statement logging re-renders through ForeignTableOption.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

  • BVT (PR suite, self-contained loopback): function/tvf_sql.sql (19 cases) and function/foreign_exttab.sql (34 cases) point the SQL kind back at the MO server itself — derivation shapes, local predicates, __mo_query projection, defaults, session-var config, prepare, ETL INSERT...SELECT, SHOW CREATE redaction, hidden-column invisibility, and all error paths. Verified live.
  • E2E (manual workflow, mirrors the MongoDB harness): make test-esql-tvf-e2e-local / .github/workflows/esql-tvf.yml stands up a single-node Elasticsearch 8.15 in docker, seeds it, boots a fresh mo-service, runs test/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).
  • Go unit: schema helper, envelope round-trip incl. hostile ;/*/ DSNs, query-list derivation (=/IN/OR/NULL/negative shapes), both CSV dialects, pruning alignment, operator, builtins, session cache (incl. concurrent under -race).
  • Regressions: tvf_parse_jsonl 18/18 (its schema helper was extracted and reused); plan/external/parsers suites green (TestBuildCreateOrReplaceViewRejectsRecursiveDefinition/future_AS_OF_timestamp fails identically at the clean upstream/main baseline 6ff9be9646 — pre-existing).

New deps: github.com/elastic/go-elasticsearch/v8 (ES client), github.com/jackc/pgx/v5 promoted to direct (postgres). Oracle / SQL Server stay behind the driver registry as follow-ups. Note: MO's fileservice replaces http.DefaultTransport, so the ES client gets an explicit http.Transport.

🤖 Generated with Claude Code

fengttt and others added 4 commits August 22, 2026 15:13
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-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 →

@fengttt

fengttt commented Aug 23, 2026

Copy link
Copy Markdown
Contributor Author

Self-review: error handling + data-type coverage

Methodology: 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 __mo_query predicate. foreign_query_list.go derives candidates from __mo_query = <expr> and evaluates <expr> on the zero-vector const-fold batch — but never checks that <expr> is column-free. The classifier accepts the hidden column on both sides, so:

select * from ft where __mo_query = __mo_query;

→ runtime error: index out of range [1] with length 0 in ColumnExpressionExecutor.Eval (reproduced; recovered by the frontend, server survives, but a panic on legal input). Same via concat(__mo_query, ''), IN items, OR branches.
Fix: require classifyFileLevelColumns(node, rhs) == (false, false) before evaluating a candidate side; otherwise treat the conjunct as non-generating (it still prunes correctly in FilterFileList, which has a real materialized batch).

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 value

The copy-based ALTER recreates the table from SHOW CREATE output, whose inline config is <redacted> — cryptic error, and with a query option the copy path could execute the foreign query for the data-copy step before failing on the read-only INSERT. Fix: mirror the MongoDB guard — IsForeignTableDef → NotSupported; do the same for datastream in passing. Related UX: ValidateConfig should recognize the literal <redacted> and say "config was redacted by SHOW CREATE; re-supply it".

R3. Get-or-connect is not atomic. Two scans sharing one config in a single query (parallel scopes; the BVT even joins two sql_tvf instances) can both miss the session cache, both Connect, and the second PutForeignConn closes the first goroutine's *sql.DB just before it calls Query → sporadic sql: database is closed on a correct query. Narrow window (cold cache + concurrent + slow ping) but structural. Fix: make Put first-wins under the session mutex and return the winner; caller closes its loser. Removes the supersede-close semantic entirely (never desired — handles are config-derived).

R4. A truncated ES HTTP response returns a silent partial result. csvparser.readBlock maps io.ErrUnexpectedEOF to "last chunk" (it must — that is io.ReadFull's normal final block), but Go's net/http surfaces premature connection close of a chunked/Content-Length body as the same io.ErrUnexpectedEOF → an ES node restart / LB idle-timeout mid-stream yields N rows and success. The sql_tvf path is safe (pw.CloseWithError carries the real driver error). Fix: wrap the ES response body in a reader that converts a stream-level ErrUnexpectedEOF into moerr ("esql: response truncated") before the parser sees it.

Data-type findings (live-probed; none of this is in the committed tests)

R5. ENGINE = ESQL + declared timestamp column fails on ES's native date format. ES|QL CSV emits ISO8601 2026-01-15T10:20:30.123Z; MO's parser accepts the T but rejects the trailing Z, and the external-table scan runs strict-mode coercion:

ERROR: the input value '2026-01-15T10:20:30.123Z' is not Timestamp type for column 0

Meanwhile esql_tvf with the same value works — the TVF param runs non-strict, whose temporal normalization handles it. That contradicts the design doc §3 ("result mapping is identical to the TVFs' schema mode"), and @timestamp is the most common ES field. Verified workaround: | EVAL ts = DATE_FORMAT(\"yyyy-MM-dd HH:mm:ss.SSS\", ts) (full round-trip incl. millis + typed predicates confirmed). Fix options: (a) targeted trailing-Z normalization for temporal columns in the ESQL dialect, (b) run the foreign scan non-strict like the TVF (but that silently degrades the column-count mismatch error the BVT asserts), (c) accept Z in the global timestamp parser. I lean (a); at minimum document the DATE_FORMAT idiom.

Verified-good (exact round-trips, live):

  • SQL kind, full matrix — bool, float32/64, decimal(18,4), date, datetime(3), timestamp(3), json with embedded commas, varbinary incl. NUL bytes (x'DEADBEEF00FF', x'00'), text with newlines/unicode/emoji/quotes/backslashes: <=>-join against the source = 0 mismatches.
  • ESQL kind — RFC 4180 doubled quotes, quoted embedded newlines, true/false → bool, empty-numeric → NULL, multivalue fields ([a, b]) into varchar.
  • Empirical unhappy paths: all-candidates-pruned → clean 0 rows; disconnect() racing an in-flight scan of the same handle is graceful (db.Close doesn't kill in-use conns; 50k rows completed, handle correctly dead after); remote-decode guarded (clear error, scan pinned to session CN); Q1 stream/goroutine lifecycle audit clean (encoder goroutine provably terminates on EOF/error/early-close/cancel).

Documented semantics worth restating in user docs: ES CSV cannot distinguish NULL from '' for string columns (numeric/temporal NULLs map correctly); TVF schema vocabulary is bool/int32/int64/float32/float64/string/timestamp only (no decimal/date/datetime/json — external tables are the full-fidelity path) and timestamp has scale 0 (truncates millis); binary values through the no-schema JSON-array mode get U+FFFD-mangled by JSON encoding (schema mode is byte-exact).

Test-coverage gaps to close

Path Covered today Missing
sql_tvf BVT int64, varchar (,/"), NULL, no-schema, errors bool/int32/float/timestamp (in vocabulary, untested), newline/unicode text e2e
ENGINE=SQL BVT bigint, varchar, decimal, datetime, derivation/prepare/ETL/errors bool, date, timestamp, json, binary, newline/unicode text
esql_tvf / ENGINE=ESQL E2E string, int64, NULL, config forms bool, float, timestamp (needs the DATE_FORMAT idiom or R5 fix), quoted-quote/newline text

Plus: duplicate column names in a schema spec silently alias to one field (add a dedup error); set @sql_tvf_config = 123 (non-string) says "not set" instead of "must be a string"; ES error-path io.ReadAll is unbounded (LimitReader); mid-stream driver errors reach the user unwrapped (internal error: invalid connection with no sql_tvf: attribution); EsqlConn.Close should CloseIdleConnections() on its private transport.

Proposed order

  1. R1 (panic), R2 (ALTER guard), R3 (connect race), R4 (ES truncation) — merge-bar.
  2. R5 ISO8601-Z handling + the small hardening items (dedup, LimitReader, error wrapping, transport close).
  3. Type-matrix test additions (BVT + E2E) per the table above — the live probes above are the templates.

🤖 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]>
@fengttt

fengttt commented Aug 23, 2026

Copy link
Copy Markdown
Contributor Author

Review findings resolved (commit 8dc02a0)

CI: all three failing checks shared one root cause — Test_funids requires new function ids in predefinedFunids; ids 571–574 registered.

Finding Resolution Evidence
R1 panic (__mo_query = __mo_query) candidate sides must be column-free; self-referential conjuncts generate nothing and prune via FilterFileList (which has a real batch) regression tests + live: both shapes now return correct rows, no panic
R2 ALTER TABLE blocked with a clear NotSupported for ESQL/SQL and datastream tables; replayed <redacted> configs now explain themselves live: clean rejection
R3 connect race PutForeignConn is first-wins under the session lock and returns the winner; the loser closes its own conn — the cache never closes a connection in use unit + 50× -race
R4 ES truncation truncationGuard remaps a transport-level io.ErrUnexpectedEOF to a hard "response truncated" error before the CSV parser can read it as end-of-data unit test with injected error
R5 ISO 8601 Z foreign ESQL scans trim the trailing Z for declared temporal columns (matches the TVF path per design doc §3) new E2E case: native ...T08:30:00.123Z → timestamp(3) with millis + typed predicates, against live ES
Hardening mid-stream driver errors wrapped with sql_tvf: attribution; ES error body via LimitReader(8192); EsqlConn.Close releases idle transport sockets; duplicate schema-spec names rejected; non-string @*_tvf_config gets a typed error unit tests each

Type-matrix coverage added (was the review's biggest gap):

  • foreign_exttab BVT: bool / float32 / float64 / decimal(18,4) / date / datetime(3) / timestamp(3) / json with embedded commas / varbinary incl. NUL bytes / unicode+newline text — with a NULL-safe-equality join asserting 0 mismatches against the source table (42/42 live).
  • tvf_sql BVT: the entire schema-spec vocabulary through both long and short specs, plus duplicate-name rejection (25/25 live).
  • E2E: seeded hired date field; exttab-iso8601-timestamp case — 17/17 against Elasticsearch 8.15.

Full validation: unit suites green (incl. Test_funids), race-clean, lint 0 issues, tvf_parse_jsonl 18/18 regression, full E2E green.

🤖 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 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.

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.

Comment thread pkg/frontend/session_foreignconn.go Resolved
Comment thread docs/cn/esql_tvf.md Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

  • Connect accepts {} even though ValidateConfig rejects 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, bounded process.ForeignConnCache interface. 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.Session methods. 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.

Comment thread pkg/sql/foreigntvf/conn.go Resolved
Comment thread pkg/sql/foreignext/config.go Resolved
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 iamlinjunhong 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.

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:

  1. [P1/security] Enforce the ESQL endpoint check on the actual connect path. pkg/sql/foreigntvf/esql.go:58-90 unmarshals the config and calls elasticsearch.NewClient without the addresses/cloudid check in validateESQLConfig (:45-53). That validator is only called for inline foreign-table DDL; esql_tvf_connect, the session-variable fallback, and scan-time configs all reach connectESQL directly through ResolveOrConnect. In go-elasticsearch v8.15, an empty config reads ELASTICSEARCH_URL and otherwise defaults to http://localhost:9200 (including URL userinfo as client credentials). Therefore a non-sys tenant can call esql_tvf_connect('{}') and bypass the new sys-only env: gate, potentially obtaining the operator-configured Elasticsearch target/credentials. Validate the endpoint inside connectESQL (or have every runtime path call the same validator) before NewClient, and add a regression that proves {} cannot inherit process defaults.

  2. [P1/Q2] Keep the session-pinned foreign scan in the distributed shuffle receiver graph. pkg/sql/compile/compile.go:2636 creates every foreign external scan with constructScopeForExternal(c.addr, false), so the source must stay on the interactive session CN. But shuffleJoinStageNodes only adds an off-worker local dependency for SINK_SCAN, and attachShuffleDispatchSource attaches 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 at compile.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:

  1. [P2/compatibility] Preserve real __mo_query columns in pre-existing schemas. pkg/catalog/types.go:115-116 makes ContainExternalHidenCol classify __mo_query globally 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 from SELECT * (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 to FOREIGN_TB plus ExternalQueryColId, 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]>
@fengttt

fengttt commented Aug 23, 2026

Copy link
Copy Markdown
Contributor Author

Review round 5 (@iamlinjunhong) — all three findings fixed (commit af78466)

1. [P1/security] ES endpoint validation on the connect path. connectESQL now runs validateESQLConfig before NewClient — every runtime path (esql_tvf_connect, session-variable fallback, scan-time configs) is covered, not just DDL. The regression sets ELASTICSEARCH_URL to a sentinel and proves '{}' and endpoint-less configs fail with "needs addresses or a cloudid" on both the direct and ResolveOrConnect paths — the process-default inheritance (and with it the env:-gate bypass) is closed. Nice catch on the go-elasticsearch default-config semantics.

2. [P1/Q2] Foreign scan in the shuffle receiver graph. Took your "include the current CN" direction via the existing SINK_SCAN mechanism: operatorTreeContainsSinkScan now also detects an External operator carrying a ForeignScan, so shuffleJoinStageNodes returns hasLocalDependency=true and appends the session CN (Mcpu=1) to the receiver stage set, letting attachShuffleDispatchSource keep the pinned scope local exactly as it does for SINK_SCAN. Regression TestShuffleStageNodesKeepForeignScanCN: query workers exclude the session CN → the stage set gains it; an ordinary scope stays fully distributed.

3. [P2/compat] Pre-existing __mo_query columns. ContainExternalHidenCol is filepath-only again; the synthetic column is identified by IsForeignQueryCol(name, ExternalQueryColId) — driving binding-level hiding in addBinding, visible-column filtering, makeFilepathBatch, and getFieldFromLine (which synthesizes only when ForeignScan is set). The CREATE/ALTER name reservation is unchanged (IsReservedExternalColName). Counterexamples added: a pre-existing REAL __mo_query column stays in SELECT * and is directly selectable; a generic external table's real __mo_query field reads source data; the foreign scan's synthetic column stays hidden.

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

fengttt and others added 2 commits August 23, 2026 14:38
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]>
@fengttt

fengttt commented Aug 23, 2026

Copy link
Copy Markdown
Contributor Author

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:

  • `foreigntvf.resolveConfigRef`, `foreignext.ResolveConfig`, and the pre-existing `datastream.ResolveAPIKey` env path are deleted; option values are used verbatim.
  • Config resolution is now simply: inline option/argument → `@esql_tvf_config` / `@sql_tvf_config` session variable → error. The session variable is the recommended way to keep credentials out of DDL/statement text.
  • SHOW CREATE and statement-log re-rendering redact every config value (the env:-verbatim carve-out is gone), and every non-empty inline config is shape-validated at CREATE time.
  • E2E updated: the cross-kind-handle case now opens a real loopback sql connection and asserts the kind-check error itself (it previously passed on an unrelated connect error).

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.

fengttt and others added 2 commits August 23, 2026 16:20
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 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 review of the current head (bfd7495). The earlier requested changes are largely addressed, but two blocking unhappy-path/compatibility defects remain:

  1. [P1][resource lifecycle] Close the private Elasticsearch transport on every failed connect. connectESQL creates a fresh http.Transport, but transfers ownership to EsqlConn only on success. The NewClient, Info, and non-2xx return paths leave no owner that can call CloseIdleConnections. This is observable, not theoretical: with an httptest endpoint returning a zero-length 401, 8 failed connectESQL calls left 8 distinct server connections in StateIdle. Each private pool can retain its socket for IdleConnTimeout (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 to EsqlConn, plus a ConnState regression test for HTTP error handshakes.

  2. [P1][compatibility/security] Do not silently reinterpret existing DATASTREAM apikey=env:NAME tables. The current base resolves this syntax at scan time via datastream.ResolveAPIKey, errors for malformed/unset references, and has regression tests. This head deletes the resolver/tests and sends ds.ApiKey verbatim. After upgrade, an existing table with apikey=env:DS_KEY sends the literal string env:DS_KEY and 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).

fengttt and others added 2 commits August 23, 2026 17:11
…: 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]>
@fengttt

fengttt commented Aug 24, 2026

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH Both P1s are fixed in 5cf7cea (pushed on top of the branch-update merge, head a150ef4):

  1. ES transport leak on failed connect — connectESQL now holds an ownership flag: until the transport is handed to EsqlConn, a deferred guard drains it with CloseIdleConnections() on every failure path (registered before the body-close defer, so LIFO order closes the response body first and then drains the idle pool). Regression TestConnectESQLFailedHandshakeClosesTransport reproduces your scenario with a ConnState-tracking httptest server returning 401: pre-fix it fails with open connections remaining after 8 failed handshakes; post-fix 0 remain. Also passed -race -count=6.

  2. DATASTREAM env:NAME apikey — no silent literal reinterpretation: both ParseTableOptions (new DDL) and DataStreamReader.Open (pre-existing persisted definitions) now fail closed via datastream.RejectEnvAPIKeyRef with an explicit "'env:NAME' apikey references are no longer supported (query processing does not read the CN process environment); recreate the table with the apikey value itself" error. On retiring the env lookup itself rather than restoring it: that is a deliberate project decision made on this PR (see the design-change comment above) — query processing takes information only from user input or the session, never os.Getenv; the datastream env path shipped very recently and the fail-closed error gives any affected table an actionable message instead of a silent auth failure. SHOW CREATE never emits the apikey, so nothing else needs migrating. Regressions: TestParseTableOptions (env: rejected at DDL) and TestDataStreamReaderRejectsEnvAPIKeyRef (persisted def rejected at scan).

On the trailing whitespace in foreign_exttab.result:29 — it is load-bearing, not lint debris: those two spaces are the empty Comment cell of the last DESC row, and mo-tester compares cell-by-cell (verified: stripping them fails the case with "one is [ ¦], but the other is []").

@iamlinjunhong Your review examined head 4ab6d9d; all three findings were fixed in the subsequent commits already on the branch before this round: (1) connectESQL validates addresses/cloudid on every runtime path before NewClient — TestConnectESQLRejectsEmptyConfig proves '{}' cannot inherit ELASTICSEARCH_URL/localhost defaults, including through ResolveOrConnect (and the env: gate it mentioned has since been removed entirely); (2) shuffleJoinStageNodes treats a ForeignScan external op like a SINK_SCAN via operatorTreeContainsSinkScan, keeping the session CN in the receiver stage set — regression TestShuffleStageNodesKeepForeignScanCN; (3) __mo_query hiding is ColId-scoped (catalog.IsForeignQueryCol(name, colId)), so a pre-existing ordinary column named __mo_query stays visible — regression TestPreexistingMoQueryColumnStaysVisible.

@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-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:

  1. [P1][correctness/Q1] CACert is a reachable panic and also breaks transport ownership. connectESQL installs a private http.Transport whose TLSClientConfig is nil, then passes a user-decoded CACert through elasticsearch.NewClient. elastictransport.New clones that transport and dereferences httpTransport.TLSClientConfig.RootCAs; a valid PEM CA config reproduced an immediate nil-pointer panic instead of a SQL error. Merely initializing TLSClientConfig is insufficient: the library clone becomes the transport that owns sockets, while EsqlConn.transport and 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.

  2. [P1][Q1-Q3] Periodic node discovery survives both failed connect and EsqlConn.Close. A non-zero DiscoverNodesInterval makes elastictransport.New install a self-rescheduling time.AfterFunc before Info. The upstream client exposes no Close/Stop method; CloseIdleConnections does not stop that timer, and DiscoverNodes sends an independent request without the caller context. With a 20ms interval and an Info endpoint returning 401, I observed a later /_nodes/http request after connectESQL had 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. Reject DiscoverNodesInterval > 0 and DiscoverNodesOnStart unless MO owns a cancelable, bounded discovery lifecycle, and cover no-post-return/no-post-close traffic.

  3. [P1][concurrency/global state] Do not allow session JSON to enable the dependency process-global debug logger. EnableDebugLogger:true writes the package-global elastictransport.debugLogger with no synchronization and never restores it. Two simultaneous connectESQL calls with that legal config produce a race-detector failure at elastictransport.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]>
@fengttt

fengttt commented Aug 24, 2026

Copy link
Copy Markdown
Contributor Author

@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 elasticsearch.Config. A strict decoder (DisallowUnknownFields) accepts only a whitelisted endpoint/credential subset — addresses, username, password, cloudid, apikey, servicetoken, certificatefingerprint, cacert — and every other field fails closed with an error naming the allowed set, on both the validate and connect paths.

  • CACert: supported, but MO-owned — the PEM is applied to MO's own transport's TLSClientConfig.RootCAs and never passed through the library's CACert field, so there is no elastictransport clone: no nil-TLSClientConfig panic, and EsqlConn.Close/the failure defer drain the transport the client actually uses. TestConnectESQLCACert covers valid-CA connect + drain-after-Close, a 401 behind the private CA draining via the failure defer, rejection without the CA, and non-PEM content.
  • DiscoverNodesInterval / DiscoverNodesOnStart: unreachable — rejected as unknown fields, so no self-rescheduling timer can ever be installed from session input.
  • EnableDebugLogger (and every other global/lifecycle knob, including ones neither of us enumerated): same — rejected, so a session can no longer write the package-global.

TestESQLConfigRejectsLifecycleKnobs pins the boundary itself. Both new tests fail on the pre-fix code; with the fix they passed -race -count=100 / -count=50 plus a full-package -race run, and the real-ES E2E is 20/20 on a fresh build (production configs use only whitelisted fields; field matching stays case-insensitive, and {} is still rejected for lacking an endpoint).

Separately, the earlier "UT Test on Ubuntu/x86" CI failure was infrastructure — the runner's onnxruntime thirdparty download timed out (curl: (28) SSL connection timeout) before any test ran; the new head re-runs everything.

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]>

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

kind/feature size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants