Skip to content

feat: ENGINE=KAFKA external table and LAST_KAFKA_MESSAGE_ID() - #27531

Merged
fengttt merged 13 commits into
matrixorigin:mainfrom
fengttt:feat-kafka-exttab
Aug 24, 2026
Merged

fengttt merged 13 commits into
matrixorigin:mainfrom
fengttt:feat-kafka-exttab

Conversation

@fengttt

@fengttt fengttt commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • Feature

Which issue(s) this PR fixes:
issue #27518

What this PR does / why we need it:

Read a Kafka topic partition through an external table, with per-message metadata columns, WHERE-driven read controls, and exactly-once consumption chaining. Design doc: docs/cn/kafka_exttab.md.

DDL

create external table kt (a int, b varchar(100)) engine = kafka with (
    'brokers' = 'host1:9092,host2:9092',  -- required
    'topic' = 'mytopic',                  -- required
    'partition' = '0',                    -- default 0
    'autocommit' = 'false',               -- default false
    'group' = 'g1',                       -- default mo_kafka_<db>_<table>
    'format' = 'csv',                     -- csv | jsonl
    'separator' = ','                     -- csv only
);

Options are validated at CREATE and persisted in the planner-owned MO_KAFKA rel_createsql envelope plus the durable features.KafkaExternal bit (envelope and bit must agree at recognition — the same anti-forgery rule as datastream/foreign tables). SHOW CREATE round-trips every option; ALTER is rejected; statement-log re-render redacts secret-shaped option keys.

Semantics

  • Each Kafka message value must parse to exactly one csv/jsonl record; anything else fails the query.
  • Synthetic columns, hidden from SELECT * and ColId-scoped so pre-existing same-named real columns keep working: __mo_message_id/ts/key/value (per-message metadata) and __mo_read_start_id/size/timeout (read controls).
  • Top-level control = const conjuncts are resolved and consumed at compile (external.DeriveKafkaReadControl): start_id is the last-consumed offset (reading begins after it; required with autocommit=false, where the position is committed before reading so a retried read is a replay; -1 = earliest; with autocommit=true 0 = earliest, -1 = latest), size caps the message count, timeout ends the read when no message arrives in time (timeout is a clean end, not an error).
  • LAST_KAFKA_MESSAGE_ID() (function id 576): session builtin returning the offset of the last message a completed scan returned (NULL before any; an aborted scan updates nothing). Feeding it back as the next __mo_read_start_id gives exactly-once chaining; with autocommit=true a completed scan commits last+1.

Execution

plan.KafkaScan (ExternType KAFKA_TB=7) rides the shared external-scan pipeline. compileKafkaScan pins the scope to the session CN (session state + ordered partition read) and joins the shuffle receiver graph like foreign scans. KafkaReader (franz-go, pure Go) streams message values as lines into the shared CSV/jsonline machinery with an order-based per-message metadata FIFO re-checked at EOF; a completed flag gates commit/session updates so an errored or cancelled scan changes nothing.

v1 limits: one partition per table, plaintext brokers (no SASL/TLS yet).

Tests

  • Unit: option/envelope round-trip; full reader semantics against an in-process kfake broker (csv, jsonl, metadata columns, positioning, size caps, commit + session-id semantics, aborted-scan no-op, malformed messages), incl. -race; control derivation; grammar (kafka stays a valid identifier; plain engine = kafka tables unaffected); DDL build / SHOW CREATE / recognition / SELECT * hiding / ALTER guard; compile dispatch + shuffle receiver pinning; builtin via the registered overload; pre-existing same-named-column compatibility.
  • BVT function/kafka_exttab (36/36): DDL, SHOW CREATE, guards, and all compile-time read-control validation — deliberately broker-free so CI is deterministic.
  • E2E (make test-kafka-exttab-e2e-local, mirrors the mongodb/esql harnesses): single-node KRaft Kafka via docker compose + fresh mo-service; 8/8 against a real broker, proving the exactly-once contract end to end — drain-to-timeout is not an error and records the right last id; chaining LAST_KAFKA_MESSAGE_ID() tiles the stream with no overlap/gap; a repeated __mo_read_start_id replays identical data; after new messages the chained read resumes at exactly the next offset; a 0-message read leaves the last id NULL in a fresh session and untouched in a chained one. The same driver script also runs broker-free as a unit test against an offset-semantics simulator, so its lines are executable in CI.

🤖 Generated with Claude Code

fengttt and others added 2 commits August 23, 2026 20:50
…origin#27518)

Read a Kafka topic partition through an external table:

- DDL: CREATE EXTERNAL TABLE ... ENGINE = KAFKA WITH (brokers, topic,
  partition=0, autocommit=false, group=mo_kafka_<db>_<table>, format
  csv|jsonl, separator). Options validated at CREATE, persisted in the
  MO_KAFKA rel_createsql envelope + features.KafkaExternal bit (both must
  agree at recognition, the datastream/foreign anti-forgery rule). SHOW
  CREATE round-trips; ALTER is rejected; statement-log re-render redacts
  secret-shaped option keys.

- Each message value must parse to exactly one csv/jsonl record (wrong field
  count, missing jsonl keys, or multi-record values fail the query).

- Synthetic columns, hidden from SELECT * and ColId-scoped so pre-existing
  same-named real columns keep working: __mo_message_id/ts/key/value
  (per-message metadata) and __mo_read_start_id/size/timeout (read
  controls). Top-level `control = const` conjuncts are resolved and consumed
  at compile (external.DeriveKafkaReadControl): start_id is the last
  consumed offset (read begins after it; required with autocommit=false,
  where the position is committed before reading so retries are idempotent;
  -1 = earliest; with autocommit=true 0 = earliest, -1 = latest), size caps
  the message count, timeout ends the read when no message arrives in time.

- Execution: plan.KafkaScan (ExternType KAFKA_TB=7) rides the shared
  external-scan pipeline; compileKafkaScan pins the scope to the session CN
  and joins the shuffle receiver graph like foreign scans. KafkaReader
  (franz-go) streams message values as lines into the shared CSV/jsonline
  machinery with an order-based per-message metadata FIFO (re-checked at
  EOF); a completed autocommit scan commits last+1 and records the last id.

- LAST_KAFKA_MESSAGE_ID() (id 576): session builtin returning the last
  message id a completed scan returned (NULL before any) — feed it back as
  the next __mo_read_start_id for exactly-once chaining.

Tests: option/envelope round-trip; full reader semantics against an
in-process kfake cluster (csv, jsonl, metadata, start/size/timeout, commit +
session-id, aborted-scan no-op, malformed messages) incl. -race; control
derivation; grammar (kafka stays a valid identifier); DDL build/SHOW
CREATE/recognition/hiding/ALTER-guard plan tests; compile dispatch + shuffle
pinning; builtin via RunFunctionDirectly; BVT kafka_exttab 36/36 on a live
server (broker-free paths). Docs: docs/cn/kafka_exttab.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
mongodb/esql-style harness (make test-kafka-exttab-e2e-local):
optools/kafka_ci.bash boots a single-node KRaft Kafka via docker compose
(host port picked up front — Kafka clients bootstrap through the ADVERTISED
listener, and the controller listener binds localhost because KRaft
implicitly advertises it and rejects 0.0.0.0) plus a fresh mo-service; the
driver (test/kafkaexttab/kafka_e2e_local.go) seeds the topic itself via
franz-go and pins one SQL connection per scenario (LAST_KAFKA_MESSAGE_ID()
is session state).

Cases (all passed against apache/kafka:3.9.0):
- read-to-end-timeout-clean: draining the stream ends by TIMEOUT, which is
  not an error — all rows return, sum checks out, last id is correct, and
  SELECT * exposes only the declared columns
- exactly-once-chaining: LAST_KAFKA_MESSAGE_ID() fed back as the next
  __mo_read_start_id tiles the stream [0-3][4-7][8-9] with no overlap/gap
- repeated-start-id-replays: the same start id twice returns identical data
  (manual commit at the position makes retries replays)
- pickup-after-produce: after 3 new messages, the chained read resumes at
  exactly the next offset
- zero-messages-null-and-preserved: a 0-message read leaves the last id
  NULL in a fresh session and UNTOUCHED in a chained one
- metadata-key-null, autocommit-earliest-and-last-id (default start is
  always earliest; committed progress is not an implicit start)

The same script also runs broker-free as a unit test against an
offset-semantics simulator (kafka_e2e_local_test.go), keeping the driver
executable in CI. Reports are local artifacts (gitignored).

Co-Authored-By: Claude Fable 5 <[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 and others added 2 commits August 24, 2026 01:56
…xorigin#27531)

Rigorous self-review of the Kafka external table (multi-lens + adversarial
verification), focused on tests, coverage, and error handling. Five
confirmed defects fixed, each with a fail-before-fix regression:

1. Out-of-range __mo_read_start_id silently reset (kgo's default
   OffsetOutOfRange reset is AtStart): a stale/typoed start id replayed the
   whole partition as "new" data. Open now fetches the partition bounds and
   fails closed — below the log start or beyond the end is a clear error —
   and ConsumeResetOffset(AtEnd) means a mid-scan retention race can only
   skip, never replay. The same bounds fetch turns an unreachable broker or
   missing topic/partition into a loud error instead of a silent empty
   result after a poll timeout.

2. A deadline on the QUERY context (max_execution_time) was conflated with
   the scan's own idle timeout: a timed-out query completed, committed
   offsets, and recorded LAST_KAFKA_MESSAGE_ID for rows the client never
   received — permanently skipping them from the exactly-once chain. Only
   the poll's own deadline is a clean end now.

3. KILL landing at a batch boundary took makeBatchRows' historical
   treat-cancel-as-EOF shortcut into the completed path, with the same
   commit/last-id corruption. A cancelled Kafka scan now aborts (plain file
   scans keep the historical behavior).

4. A truncated-JSON message rode the streaming-LOAD "wait for next chunk"
   resume: fragments merged with the NEXT message or silently dropped rows
   at EOF, then committed past the corruption. Now a hard error.

5. int64 control values could overflow: a huge __mo_read_timeout wrapped
   time.Duration negative (instant empty result); __mo_read_start_id =
   MaxInt64 wrapped +1 negative (replay from earliest). Bounded at derive.

Plus: the Close-path autocommit commit is bounded (15s) and logged instead
of unbounded and silent; and server-side exactly-once chaining
(where __mo_read_start_id = last_kafka_message_id()) now works — the
builtin is whitelisted in the compile-time classifier (mo_log_date
precedent), proven end-to-end by the E2E chain case which now uses it.

Coverage: changed-line UT coverage raised (control-eval type matrix, offset
matrix cells OFF/-1 ON/-1 ON/n, session state, seedKafka via kfake,
timestamp instant preservation across session zones); BVT extended with
overflow caps, INSERT rejection, DESC, and CREATE TABLE LIKE (46/46);
real-broker E2E 8/8 including the server-side chain.

Co-Authored-By: Claude Fable 5 <[email protected]>
@fengttt

fengttt commented Aug 24, 2026

Copy link
Copy Markdown
Contributor Author

Self-review completed (multi-lens discovery + adversarial verification + personal closure walks, focused on tests, coverage, and error handling). Five confirmed defects fixed in 0c993ed's fix commit, each with a fail-before-fix regression:

  1. [blocking] Out-of-range __mo_read_start_id silently replayed the partition. kgo's default OffsetOutOfRange reset is AtStart, so a stale/typoed start id returned the entire topic as "new" data. Open now fetches the partition's real bounds and fails closed (below log start / beyond end are clear errors), with ConsumeResetOffset(AtEnd) so a mid-scan retention race can only skip, never replay. The same bounds fetch makes an unreachable broker or a missing topic/partition a loud error instead of a silent empty result — closing three findings with one mechanism.
  2. [blocking] Query deadline conflated with the scan's idle timeout. A max_execution_time deadline was treated as a clean end-of-stream: the timed-out query committed offsets and recorded LAST_KAFKA_MESSAGE_ID for rows the client never received — permanently skipping them from the exactly-once chain. Only the poll's own deadline is a clean end now.
  3. [blocking] KILL at a batch boundary completed the scan. makeBatchRows' historical treat-cancel-as-EOF shortcut gave a killed Kafka scan commit side effects. Cancelled Kafka scans now abort; plain file scans keep the historical behavior.
  4. [blocking] Truncated-JSON message rode the streaming-LOAD resume path — fragments merged with the next message or valid rows silently dropped at EOF, then committed past the corruption. Now a hard "not a complete JSON object" error.
  5. int64 control overflow: huge __mo_read_timeout wrapped time.Duration negative (instant empty result); start_id = MaxInt64 wrapped +1 negative (replay from earliest). Bounded at derive time.

Also: the Close-path autocommit commit is now bounded (15s) and logged instead of unbounded and silent, and server-side exactly-once chaining works — where __mo_read_start_id = last_kafka_message_id() (the builtin is whitelisted in the compile-time classifier under the mo_log_date precedent; the review's test-gap finding caught that this path errored, and the E2E chain case now exercises it end-to-end).

Coverage (addressing the two failing CI coverage checks): measured changed-line UT coverage locally and raised it from ~68% to ~75% UT-only (CI adds BVT + cross-package coverage on top) — control-eval type matrix, the missing offset-matrix cells (OFF/-1, ON/-1, ON/n), session-state test, seedKafka against kfake, and a timestamp instant-preservation test across session zones. BVT extended to 46/46 (overflow caps, INSERT rejection, DESC, CREATE TABLE LIKE); real-broker E2E 8/8 including the server-side chain.

One finding was adversarially refuted (prepared-EXECUTE control reuse: external scans recompile per EXECUTE), and the decision log records the accepted behaviors: LIMIT-stopped scans deliberately don't commit or update the last id (replay-not-skip), an empty completed read commits nothing, and the remote-run field copy is covered by compile-layer tests since the scan is session-CN-pinned by construction.

@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 at exact head 29a1043. I reread every review, issue-level author reply, and all four prior inline threads, compared the delta from my previously reviewed head 41ac3e8, and audited the complete feature diff. The four prior findings are closed in code: progress now waits for the frontend statement terminal, messages are parsed independently, partition-level commit responses are checked, and size 0 is accepted. The reusable CSV parser also removes the reported per-message allocation cost without cross-input state bleed. One newly identified multi-broker availability blocker remains inline. Validation on this exact head: all affected package suites passed; Kafka/CSV/frontend/compile/builtin focused tests passed under race at count 3; go vet and git diff --check passed; merge-tree against the exact base is clean. An independent kfake failover counterexample reproduced the inline failure in all three runs; the temporary test was removed.

// validate an explicit start id (below the log start or beyond the end
// is an error, never a silent reset) and resolve the -1/earliest
// boundary without a second admin round-trip.
seedCl, err := kgo.NewClient(kgo.SeedBrokers(strings.Split(ks.Brokers, ",")...))

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] Normalize every broker entry before constructing both clients. ParseTableOptions validates each entry with strings.TrimSpace, but stores the original comma-separated value, while this call and the data-client call at line 321 pass raw strings.Split results to franz-go. I used the accepted configuration brokers="127.0.0.1:1, ": with the first seed unavailable, all three runs failed with "lookup 127.0.0.1: no such host" because the healthy seed retained its leading space. Thus a conventional comma-space broker list loses failover and makes the Kafka table unreadable precisely when the first broker is down. Canonicalize the list when parsing or use one shared splitter that trims every seed, and add a dead-first/healthy-second regression.

Review (aptend): ParseTableOptions VALIDATED each broker entry trimmed but
STORED the raw comma-separated value, and both client constructions passed
raw strings.Split results to franz-go — so a conventional comma-space list
("dead:1, healthy:9092") kept the healthy seed's leading space, its DNS
lookup failed, and failover was lost precisely when the first broker was
down.

Two layers: ParseTableOptions now canonicalizes the stored list (trimmed,
comma-joined — new tables and SHOW CREATE carry the clean form), and a
shared kafkaSeeds splitter trims every entry at client construction so
pre-existing envelopes written before canonicalization also fail over.

Regressions (both fail on the pre-fix code): the dead-first/healthy-second
comma-space failover read against kfake, and the parse-time
canonicalization assert. Race-stressed focused -count=3 + full-package
-race; lint clean.

Co-Authored-By: Claude Fable 5 <[email protected]>
@fengttt

fengttt commented Aug 24, 2026

Copy link
Copy Markdown
Contributor Author

@aptend Fixed in the just-pushed commit, at both layers: ParseTableOptions now canonicalizes the stored broker list (each entry trimmed, comma-joined — new tables and SHOW CREATE carry the clean form), and a shared kafkaSeeds splitter trims every entry at client construction for both clients, so a pre-existing envelope written before canonicalization fails over too.

The requested dead-first/healthy-second regression is TestKafkaReaderBrokerFailover: brokers = "127.0.0.1:1, <healthy kfake addr>" (comma-space form) reads both messages through the healthy second seed — it fails on the pre-fix code with exactly the lookup failure you reproduced. The parse-time canonicalization has its own assert (h1:9092 , h2:9092 → h1:9092,h2:9092). Both race-stressed, full-package -race and lint clean.

@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 34a3898a4c25673b47002bbb67e20de124253f51 against merge-base b284c710e1da8854d6c28b4dfe8531731b7194ab; current origin/main is 0aa7fc0b584eefaf93a925ece0eea8e39493e0a2, and the merge-tree is clean.

One P1 transactional-correctness blocker remains; details are inline. I traced the Kafka progress ownership path from reader drain through External.Reset, the session queue, and the frontend statement/transaction terminals, and reviewed the DDL, planner/compile, remote-copy, parser, lifecycle, and test paths. The broker-free Kafka E2E simulator passed. Local MO package tests were blocked before assertions by missing native CGo prerequisites (libmo and third-party headers); the PR checks are all complete with the reported summary passing.

Comment thread pkg/frontend/mysql_cmd_executor.go Outdated
// pipeline (including downstream consumers on split scopes) has finished
// by the time executeStmtWithMaxExecutionTime returns, so publish on
// success and discard on failure here — never earlier.
ses.FinalizeKafkaProgress(err == nil)

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] Defer Kafka progress until the enclosing explicit transaction commits. This line treats a nil return from executeStmtWithMaxExecutionTime as the publication terminal, but under BEGIN / autocommit=0, finishTxnFunc calls TxnHandler.Commit, whose multi-statement branch at pkg/frontend/txn.go:742-758 deliberately leaves the transaction uncommitted. A concrete failure is BEGIN; INSERT INTO dst SELECT ... FROM kafka_t WHERE __mo_read_start_id = ...; ROLLBACK;: the INSERT reaches this line and publishes LAST_KAFKA_MESSAGE_ID (and, for a Kafka table with autocommit enabled, commits last+1), then ROLLBACK discards the destination rows. The next chained read starts after the published id and permanently skips those messages. Keep pending progress owned by the transaction until COMMIT/ROLLBACK (or otherwise prevent Kafka-backed DML from publishing inside an uncommitted transaction), and add a regression for successful DML followed by rollback.

Review (iamlinjunhong): the statement terminal published deferred Kafka
progress on statement success, but under BEGIN / autocommit=0 the
statement's commit is deliberately deferred — so BEGIN; INSERT INTO dst
SELECT ... FROM kafka_t ...; ROLLBACK published LAST_KAFKA_MESSAGE_ID (and,
with autocommit=true, committed last+1) for rows the rollback then
discarded, permanently skipping those messages from the chain.

Ownership moves to the TRANSACTION terminal: TxnHandler.Commit publishes on
the actual-commit path's success and discards on commit failure; every
rollback path (full transaction or statement-level within one) discards;
the multi-statement deferring branch leaves progress queued with the open
transaction; the statement terminal only discards on statement error. For
single-statement autocommit the queue is populated by the pipeline Reset
before finishTxnFunc commits, so publication ordering is unchanged there.

Regression (E2E, real broker, 9/9): BEGIN; INSERT..SELECT FROM an
autocommit=true kafka table with a fresh group; LAST_KAFKA_MESSAGE_ID() is
NULL while the transaction is still open, ROLLBACK leaves it NULL with no
committed group offset and zero destination rows, and the identical
statement followed by COMMIT publishes the last id (12), the group offset
(13), and the 13 rows. The broker-free simulator models
BEGIN/COMMIT/ROLLBACK staging so the same script runs as a unit test.

Co-Authored-By: Claude Fable 5 <[email protected]>
@fengttt

fengttt commented Aug 24, 2026

Copy link
Copy Markdown
Contributor Author

@iamlinjunhong Fixed in 2440c61: deferred Kafka progress is now owned by the transaction, not the statement.

  • TxnHandler.Commit's actual-commit path publishes on success and discards on commit failure; the multi-statement deferring branch you pointed at (txn.go commit rules) leaves the progress queued with the open transaction.
  • Every rollback path — full transaction or statement-level within one — discards.
  • The statement terminal in executeStmtWithResponse now only discards on statement error; success publication happens exclusively at the transaction terminal. For single-statement autocommit the queue is populated by pipeline Reset before finishTxnFunc commits, so ordering there is unchanged.

Your exact scenario is the new E2E regression (txn-rollback-discards-commit-publishes, passed against a real Kafka broker, 9/9 overall): BEGIN; INSERT INTO dst SELECT ... FROM an autocommit=true Kafka table with a fresh consumer group — LAST_KAFKA_MESSAGE_ID() is NULL while the transaction is still open (mid-txn assert), ROLLBACK leaves it NULL with no committed group offset (verified via kadm) and zero destination rows, and the identical statement followed by COMMIT publishes the last id (12), the group offset (13), and the 13 rows. The broker-free simulator models BEGIN/COMMIT/ROLLBACK staging so the same script also runs as a CI unit test. Frontend suite and lint green.

Conflicts were only the three generated files (plan.pb.go, pipeline.pb.go, mysql_sql.go), regenerated via make pb and the parser Makefile. No semantic collisions: KAFKA_TB=7, ExternScan field 15, pipeline field 26, and function id 576 all remain unclaimed by main (incl. the new ASOF JOIN work). Kafka/foreign suites, Test_funids, external, frontend all green post-merge.

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.

6 participants