Skip to content

feat: datastream external table (ENGINE = DATASTREAM) [port to 4.2-dev of #27469] - #27479

Merged
fengttt merged 2 commits into
matrixorigin:4.2-devfrom
fengttt:port-datastream-4.2-dev
Aug 22, 2026
Merged

fengttt merged 2 commits into
matrixorigin:4.2-devfrom
fengttt:port-datastream-4.2-dev

Conversation

@fengttt

@fengttt fengttt commented Aug 22, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #27468

What this PR does / why we need it:

Ports the datastream external table (CREATE EXTERNAL TABLE ... ENGINE = DATASTREAM)
to 4.2-dev. This is a cherry-pick of #27469 (merged to main as a826c02)
with the small adaptations 4.2-dev requires:

  • build_show_util.go: 4.2-dev's SHOW CREATE does not thread sqlMode, so
    formatDataStreamTableOptionsForShowCreate and its call site use the
    no-sqlMode formatStrInSingleQuotes / getRewriteSQLStmt convention.
  • filter deparser: 4.2-dev's plan.Literal has no IsSerialized field; the
    IsBin + printable + backslash guards still cover the unsafe-literal cases.
  • plan.pb.go / pipeline.pb.go / mysql_sql.go regenerated from the merged
    proto/grammar (adding the DataStreamScan message renumbers descriptor
    indices — mechanical, same as on main).

Feature summary (unchanged from #27469): a streaming gRPC data-load bridge —
MO reads CSV chunks from a server described by WITH ('server','port','table', 'recheck','apikey'), reusing the CSV external scan operator via a
DataStreamReader; conservative filter pushdown (only under recheck=false,
''-doubled quoting, backslash literals refused); optional API-key auth with
an env:NAME reference that keeps the secret out of the catalog; and a Java
reference server xtool/jstfu (jdbc + file sources, bounded/cancellable
streaming). See docs/cn/stream_transport_fast_upload.md and
xtool/jstfu/README.md.

Validated on this branch: full go build ./..., datastream unit tests
(parser, deparser, config/ResolveAPIKey, plan, frontend redaction), and jstfu
Java build all green. BVT (test/distributed/cases/datastream) and the e2e
harness (test/datastream) are carried over unchanged and run in CI.

🤖 Generated with Claude Code

…GINE = DATASTREAM) (matrixorigin#27469)

- [ ] API-change
- [ ] BUG
- [ ] Improvement
- [ ] Documentation
- [x] Feature
- [ ] Test and CI
- [ ] Code Refactoring

issue matrixorigin#27468

Implements the datastream external table — a generic streaming data-load
bridge (`CREATE EXTERNAL TABLE ... ENGINE = DATASTREAM`) that reads
CSV-encoded chunks from a gRPC server, with a Java reference server
bridging the Java ecosystem (first candidate per the issue). Design
spec:
`docs/cn/stream_transport_fast_upload.md`; implementation plan and
as-built
notes: `docs/cn/stream_transport_fast_upload_plan.md`.

```sql
CREATE EXTERNAL TABLE t (col1 int, col2 timestamp, col3 varchar(100), col4 text)
ENGINE = DATASTREAM WITH (
    'server' = 'grpc_server_ip', 'port' = '4444',
    'table' = 'the_table_to_read_from', 'recheck' = 'true');
SELECT * FROM t WHERE col2 > '2020-11-11 00:00:00';
```

**MO side** (mirrors the `ENGINE = MONGODB` seams throughout):
- Parser: `datastream_table_param` grammar +
`tree.DataStreamTableParam`;
  `datastream` stays a non-reserved keyword.
- DDL: new `pkg/sql/datastream` package validates options
  (`server`/`port`/`table`/`recheck`) and stores a planner-owned
  `/* MO_DATASTREAM: ... */` envelope in `rel_createsql`, guarded by a
durable `features.DataStreamExternal` bit (envelope and bit must agree).
  SHOW CREATE TABLE round-trips.
- Plan: `ExternType_DATASTREAM_TB` + `plan.DataStreamScan` carried on
  `ExternScan`; remote-run wired through `pipeline.ExternalScan`.
- Predicate pushdown: a conservative `plan.Expr` → MySQL-text deparser
(comparisons, AND/OR/NOT, IN, BETWEEN, IS [NOT] NULL, LIKE over columns
and literals). The pushed text is a hint; with `recheck='true'`
(default)
  MO re-applies every filter locally. `recheck='false'` skips local
  re-evaluation for exactly the conjuncts that were pushed, so
  non-deparsable conjuncts always stay local and results can never be
  wrong-by-omission.
- Execution reuses the CSV external scan operator wholesale: a new
`DataStreamReader` (an `ExternalFileReader`) wraps the gRPC chunk stream
  as an `io.Reader` feeding the existing CSV parser and batch builder,
  using the INLINE virtual-single-file convention.

**Wire contract**: `proto/datastream/v1/datastream.proto` (plain proto3,
shared between the Go client and the Java server). Server-streaming
`Read`;
chunks carry only complete CSV records; errors surface both as gRPC
status
and as a terminal `Error` frame (TABLE_NOT_FOUND / DATASOURCE_ERROR).

**Java reference server** `xtool/jstfu` (Maven, shaded jar via `make
jstfu`,
Java 8 bytecode so it runs on the CI/tester JDK 8; Maven wrapper
included so
runners without Maven can build):
- **jdbc** datasource: runs configured SQL with `${FILTER}` replaced by
the
  pushed predicate text (`1=1` when absent), streams rows as CSV.
- **file** datasource: streams an existing CSV re-chunked at record
boundaries (quote-state aware, so quoted embedded newlines never split);
  filter hint is a documented noop.

**Tests**
- Go unit: deparser table tests, envelope/options, DataStreamReader
against
an in-process fake gRPC server (multi-chunk, error frames, cancellation,
  record-spanning-chunk tolerance).
- Java unit: chunker record-boundary invariant, `${FILTER}`
substitution,
  config validation.
- `test/datastream`: self-contained e2e (starts the jar itself)
including a
  full MatrixOne round-trip: file + jdbc scans, pushdown with recheck
  on/off, error propagation, ETL insert, parallel load with disjoint
  filters, and a 2KB-chunk multi-chunk streaming test that asserts every
  chunk boundary is record-aligned.
- BVT `test/distributed/cases/datastream`: DDL validation, file + jdbc
scans, NULL handling on a 20-column fixture with quoted embedded
newlines
(byte-identical vs LOAD DATA), AND/OR/IN/BETWEEN/NOT/LIKE pushdown with
  recheck=true/false equivalence, bulk ETL, and error conditions
  (table-not-found, bad file, jdbc SQL error, connection refused).

**CI wiring**
- Standalone/launch BVT: `optools/run_bvt.sh` builds the jar (Maven
  wrapper) if needed and starts jstfu on `127.0.0.1:4444` before BVT;
  idempotent across the restart pass.
- Compose BVT: `jstfu-build` service (maven image) builds the jar into a
shared volume; `jstfu-cn0`/`jstfu-cn1` sidecars share each CN's network
namespace so `127.0.0.1:4444` resolves on whichever CN compiles the
scan,
  and the jdbc datasources loop back to the CN's own `127.0.0.1:6001`.
Resources are mounted at `/jstfu-test` so the CI `:/test` mount rewrite
cannot break the server's file paths. `docker compose up -d` blocks
until
  the jar build completes, so BVT cannot start before jstfu is servable.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5 <[email protected]>
(cherry picked from commit a826c02)
@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 →

…COLLATE)

On 4.2-dev, SHOW CREATE for an external table does not emit the
per-column 'COLLATE utf8mb4_general_ci' clause that main emits (main's
CharsetLegacy sentinel is not present on 4.2-dev). The datastream.result
was generated on main; drop the COLLATE clauses from the three SHOW
CREATE blocks (ext_file, ext_jdbc_norecheck, ext_keyed) to match 4.2-dev
output. Fixes the compose-pessimistic BVT (3/43) and the cascaded
Coverage-merge failure on matrixorigin#27479.

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.

Reviewed exact head 0987b1d as a 4.2-dev port of merged main commit a826c02. All newly added source files are byte-identical to the merged implementation except the documented Literal/SHOW CREATE adaptations; protobuf tags are collision-free, the 4.2 SHOW CREATE golden adjustment is consistent, and focused datastream, external, compile, plan, and frontend tests pass. One blocking bounded-streaming/protocol issue remains in the inherited implementation.

record.append(encodeField(values[i]));
}
record.append('\n');
buffer.write(record.toString().getBytes(StandardCharsets.UTF_8));

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.

P1 — A legal large row exceeds the client wire limit and can exhaust the jstfu heap. The Go reader hard-caps each received gRPC message at 32 MiB, but CsvChunker only checks chunkSize after it has built and appended an entire record. The wire contract also forbids splitting a record across chunks. A single legal TEXT/LONGTEXT value larger than 32 MiB is therefore materialized through StringBuilder/String/UTF-8/ByteArrayOutputStream copies and emitted as one oversized response; MO then fails the scan with ResourceExhausted. Concurrent large rows amplify the transient copies into server OOM. FileSource has the same whole-record buffering boundary. I reproduced this with a temporary focused test: a 32 MiB + 1 field under the default 1 MiB chunk target emits a chunk above the MO receive cap; the test fails deterministically and was removed. Make the configured chunk size a real hard bound (the Go grpcChunkReader already tolerates records spanning responses, so relaxing the whole-record contract is viable), or reject oversized records before unbounded allocation with a controlled error below the wire cap. Cover both JDBC and file sources at the 32 MiB boundary.

@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 0987b1d94b4ddd81d28d37871a5e9448961ee0f1 against base 01ae8eca88110dc29d2f51e421570bb3d850d328 (merge-base is the base commit). No P0 found, but three P1 blockers remain:

  1. The existing unresolved thread at CsvChunker.java:47 proves that one legal row larger than 32 MiB is buffered through multiple full-size copies, then emitted above the Go client receive cap. This deterministically fails the scan and concurrent rows can OOM jstfu; FileSource has the same whole-record accumulation. #27479 (comment)
  2. pkg/frontend/mysql_cmd_executor.go:333: API-key redaction only runs after a CreateTable AST exists. The parse-error path records raw SQL and leaks a literal key on an ordinary syntax error (inline comment).
  3. xtool/jstfu/src/main/java/io/matrixone/jstfu/source/JdbcSource.java:59: connection establishment occurs before cancellation owns a closeable, with no connection timeout supplied by this feature (inline comment). A blackholed JDBC endpoint can occupy all bounded worker slots despite client cancellation.

The 32 check runs are completed and the required summary is successful, but CI does not exercise these boundary/unhappy paths. The 4.2-specific Literal and SHOW CREATE adaptations otherwise match the branch contracts. Per the review gate, any surviving P1 requires REQUEST_CHANGES.

case *tree.CreateIcebergCatalog, *tree.AlterIcebergCatalog,
*tree.CreateMongoDBConnection, *tree.AlterMongoDBConnection:
return tree.String(statement, dialect.MYSQL)
case *tree.CreateTable:

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.

P1 — malformed DATASTREAM DDL can leak the API key into statement logs. This branch only runs after parsing produced a CreateTable AST. On a syntax error, RecordParseErrorStatement calls RecordStatement with cw == nil (:407), and that path records envStmt unchanged (:207-210). For example, a CREATE containing apikey = prod-secret followed by a typo is persisted with the literal credential, despite the feature promise that statement logs redact it. Please add a raw-SQL/lexer-aware redaction before parse-error recording and cover the actual parse-error path.

@Override
public void stream(String filter, StreamContext ctx) throws Exception {
String sql = substituteFilter(config.sql, filter);
try (Connection conn = DriverManager.getConnection(config.connectionString, config.user, config.password);

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.

P1 — cancellation cannot terminate a blocked JDBC connection attempt. DriverManager.getConnection must return before the connection is registered at line 63. The new querytimeoutseconds only applies to the later Statement, and the documented/example URLs have no connectTimeout; therefore a blackholed endpoint can remain in getConnection with no registered resource for Cancellation.cancel() to close. Future.cancel(true) only interrupts the worker and does not provide a bound for a blocking JDBC socket connect. Repeating this across maxconcurrentreads consumes every worker and makes healthy datasources return server-busy. Bound/cancel connection establishment itself and add a blocking-driver regression.

@fengttt
fengttt merged commit 27fb0a7 into matrixorigin:4.2-dev Aug 22, 2026
32 checks passed
fengttt added a commit that referenced this pull request Aug 28, 2026
…v of #27489, #27531, #27517, #27710, #27611] (#27769)

## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [ ] Improvement
- [ ] Documentation
- [x] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue #27488, issue #27518, issue #27517, issue #27610

## What this PR does / why we need it:

Ports the external-table feature series from `main` to **4.2-dev**, plus
the
MySQL SQLSTATE / txn-fatal-error work that depends on it, as five
separate
cherry-picks in their original order. This stacks on the datastream
external
table already in 4.2-dev (#27479).

| Ported commit | Feature |
| --- | --- |
| `861a0f5ea6` (#27489) | `esql_tvf` / `sql_tvf` table functions and
`ENGINE = ESQL|SQL` foreign external tables |
| `6742f958d4` (#27531) | `ENGINE = KAFKA` external table and
`LAST_KAFKA_MESSAGE_ID()` |
| `3a3a80185b` (#27517, #27609) | error mode for external tables —
`__mo_file_line` / `__mo_error_message` / `__mo_error_text` |
| `1d3483ac97` (#27710) | opt-in predicate pushdown for `ENGINE = SQL`
external tables |
| `745d8364c5` (#27611) | MySQL SQLSTATEs, opt-in txn-fatal errors
(`mo_rollback_txn_on_error`), typed `mo.sql` errors |

Each commit message records its own adaptations; they are summarised
here
because they are the whole review surface — no behaviour was redesigned
for
4.2-dev.

### Adaptations 4.2-dev required

- **`build_show_util.go` — no `sqlMode` threading.** 4.2-dev's SHOW
CREATE uses
`formatStrInSingleQuotes` / `getRewriteSQLStmt`, not the `...ForSQLMode`
variants. The new Kafka and foreign-table option formatters, their call
sites, and their unit tests use the 4.2-dev convention. This is the same
  adaptation the datastream port (#27479) made.
- **`plan.Type` has no `Charset` field.** The `__mo_query` hidden
column, the
synthetic Kafka columns, and the error-mode varchar columns are built
like
  their sibling hidden columns in 4.2-dev.
- **Function id renumbering.** 4.2-dev has fewer builtins, so
  `ESQL_TVF_CONNECT` / `ESQL_TVF_DISCONNECT` / `SQL_TVF_CONNECT` /
`SQL_TVF_DISCONNECT` become 563–566 and `LAST_KAFKA_MESSAGE_ID` becomes
567,
with `FUNCTION_END_NUMBER` 568. The main-only `uuid_v*` name-map entries
are
  not part of this port.
- **Main-only context dropped from conflict regions.**
  `constructMongoScanScope` (compile.go), `remapRegularIndexPreInsert`
(query_builder.go) and the temp-table `commitTempTableStatement` branch
(txn.go) do not exist in 4.2-dev and were swept into conflict hunks;
only the
  intended additions were kept. `mysql_cmd_executor.go` likewise keeps
  4.2-dev's `executeStmtWithTxn` call and adds only the Kafka
  `FinalizeKafkaProgress(false)` failure belt.
- **#27611 rides along because it depends on this series.** It updates
  `test/distributed/cases/function/foreign_exttab.result` (`Error 1146
(HY000)` -> `Error 1146 (42S02)`), a file that only exists once #27489
is
ported, so it cannot go in a standalone PR against today's 4.2-dev. Its
own
  adaptations: main-only `countUpdateChangedRows` dropped from the
  `mysql_cmd_executor.go` conflict hunk (only
  `rollbackWholeTxnOnPreExecutionError` is added); `ErrDuplicateEntry` /
  `ErrWrongValueCountOnRow` / `ErrBadFieldError` take the real SQLSTATEs
23000 / 21S01 / 42S22, which 4.2-dev still had on
`MySQLDefaultSqlState`;
  and the `CODEOWNERS` hunk is dropped, since it fixes a typo in a
  `/pkg/fulltext2` owner line 4.2-dev does not have.
- **Generated files are regenerated, not merged.** `mysql_sql.go`,
  `plan.pb.go` and `pipeline.pb.go` are rebuilt from the merged `.y` /
`.proto` sources. The grammar regenerates with zero shift/reduce
conflicts.

### Known gap: #27593 is NOT included

Main commit `0f10095703` — *fix(kafka): use explicit transaction
checkpoints*
(#27593) — lands between commits 2 and 3 of this series and is **not**
ported
here. It is a follow-up fix to the Kafka external table touching
production
code (`session_kafka.go`, `txn.go`, `external.go`, `kafka/config.go`,
`process/types.go`), so **4.2-dev's Kafka engine keeps the original
implicit-commit progress path**.

Because main's error-mode Kafka E2E cases were written on top of that
fix,
they are adapted back to the pre-checkpoint harness (`pendLastSet`
rather than
`pendCheckpointSet`) and the `kafka_checkpoint` `last_id` case is
dropped. All
other error-mode cases are kept, including the negative control.

I confirmed by diffing the ported files against `1d3483ac97` that #27593
is the
only functional drift from main; the one remaining difference
(`foreigntvf/esql.go`) is a comment-only change from the unrelated
fileservice
commit `1909f795c8`. Happy to port #27593 as a follow-up if you want
4.2-dev
to match main.

## Testing

`go build ./...` and `go vet ./pkg/... ./test/...` clean; `gofmt` clean
across
all 127 changed files.

Unit suites passing on this branch:

`sql/foreignext`, `sql/foreigntvf`, `sql/kafka`, `sql/datastream`,
`sql/plan`,
`sql/plan/function`, `sql/colexec/external`,
`sql/colexec/table_function`,
`sql/util/csvparser`, all `sql/parsers` dialects, `catalog`,
`common/moerr`,
the full `frontend` suite, `vm/process`, `test/kafkaexttab` (including
`TestRunErrorModeAgainstSimulator` and the
`TestRunErrorModeDetectsAWrongSplit`
negative control) and `test/esqltvf`.

For #27611 specifically: its new tests pass (`TestSqlStateMatchesMySQL`,
`TestDuplicateEntrySqlState`, `Test_isErrorRollbackWholeTxn`,
`TestNewErrorRollbackWholeTxnCoversEveryCode`,
`TestRollbackTxnOnErrorVarDefinition`,
`TestPreExecutionRollbackIsGuarded` and
the six typed `mo.sql` error tests). Because the SQLSTATE change
ripples, I
also checked the blast radius: `sql/plan` and `sql/plan/function`, which
assert
hardcoded SQLSTATEs, pass; and the BVT files containing `HY000` carry it
only
inside `--ERROR` comments that mo-tester ignores, for error numbers
outside the
changed set.

BVT cases and resources are ported with the commits
(`function/foreign_exttab`, `foreign_exttab_pushdown`,
`foreign_conn_limit`,
`tvf_sql`, `kafka_exttab`, `table/external_table_error_mode{,_load}`,
`pessimistic_transaction/rollback_txn_on_error`,
`procedure/starlark_sql_error`); I have
not run the BVT suite locally — leaving that to CI.

---------

Co-authored-by: Claude Opus 5 (1M context) <[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.

4 participants