Repository navigation
feat: ENGINE=KAFKA external table and LAST_KAFKA_MESSAGE_ID() - #27531
Conversation
…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 reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
…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]>
… feat-kafka-exttab
|
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:
Also: the Close-path autocommit commit is now bounded (15s) and logged instead of unbounded and silent, and server-side exactly-once chaining works — 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, 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
left a comment
There was a problem hiding this comment.
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, ",")...)) |
There was a problem hiding this comment.
[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]>
|
@aptend Fixed in the just-pushed commit, at both layers: The requested dead-first/healthy-second regression is |
iamlinjunhong
left a comment
There was a problem hiding this comment.
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.
| // 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) |
There was a problem hiding this comment.
[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]>
|
@iamlinjunhong Fixed in 2440c61: deferred Kafka progress is now owned by the transaction, not the statement.
Your exact scenario is the new E2E regression ( |
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]>
What type of PR is this?
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
Options are validated at CREATE and persisted in the planner-owned
MO_KAFKArel_createsql envelope plus the durablefeatures.KafkaExternalbit (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
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).control = constconjuncts are resolved and consumed at compile (external.DeriveKafkaReadControl):start_idis the last-consumed offset (reading begins after it; required withautocommit=false, where the position is committed before reading so a retried read is a replay;-1= earliest; withautocommit=true0= earliest,-1= latest),sizecaps the message count,timeoutends 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_idgives exactly-once chaining; withautocommit=truea completed scan commitslast+1.Execution
plan.KafkaScan(ExternTypeKAFKA_TB=7) rides the shared external-scan pipeline.compileKafkaScanpins 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; acompletedflag 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
kfakebroker (csv, jsonl, metadata columns, positioning, size caps, commit + session-id semantics, aborted-scan no-op, malformed messages), incl.-race; control derivation; grammar (kafkastays a valid identifier; plainengine = kafkatables 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.function/kafka_exttab(36/36): DDL, SHOW CREATE, guards, and all compile-time read-control validation — deliberately broker-free so CI is deterministic.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; chainingLAST_KAFKA_MESSAGE_ID()tiles the stream with no overlap/gap; a repeated__mo_read_start_idreplays 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