Skip to content

feat: error mode for external tables — __mo_file_line / __mo_error_message / __mo_error_text (#27517) - #27609

Merged
fengttt merged 16 commits into
matrixorigin:mainfrom
fengttt:feat-exttab-error-mode
Aug 27, 2026
Merged

fengttt merged 16 commits into
matrixorigin:mainfrom
fengttt:feat-exttab-error-mode

Conversation

@fengttt

@fengttt fengttt commented Aug 25, 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 #27517

What this PR does / why we need it:

A scan of an external table fails the whole statement on the first record it cannot parse. One bad line in a million-line file means no result at all, and no way to find out which line it was without reading the file by hand.

This adds an error mode: a bad record becomes a row instead of a failure. It is switched on by asking for it — by selecting one of two columns the query would otherwise not mention.

The columns

Three hidden columns exist on every text-backed external table (EXTERNAL, KAFKA, DATASTREAM, foreign). They do not appear in select *, desc, or show create table, and their names are reserved so a user table cannot declare them.

Column Type Meaning
__mo_file_line bigint the physical line the record starts on (NULL for Kafka, which has no lines)
__mo_error_message varchar why the record failed, NULL if it parsed
__mo_error_text varchar the record as written in the source, NULL if it parsed
create external table t (a int, s varchar(20))
  infile{'filepath'='/data/rows.csv'};

-- unchanged: fails on the first bad record
select * from t;

-- reports them instead
select a, s, __mo_file_line, __mo_error_message, __mo_error_text from t;

-- the two halves of a load
insert into good    select a, s from t where __mo_error_message is null;
insert into rejects select __mo_file_line, __mo_error_message, __mo_error_text from t
                    where __mo_error_message is not null;

On a failed row every user column is NULL — including one that happened to convert before the failure, because the record is not trustworthy — while every column the scan synthesizes keeps its value: __mo_filepath, __mo_file_line, and the Kafka metadata columns. Those are what let a user find the record again.

What switches it on

__mo_error_message and __mo_error_text turn tolerance on. __mo_file_line deliberately does not: it is position metadata, and per the issue a query that only wants line numbers must still fail on a bad record. The decision is made once per scan in resolveExternalErrorMode, from the attribute list the operator was given — column pruning has already run, so a query that does not mention the columns takes the historical path with no per-row test to pay for. It is keyed on the reserved column ids, not the names.

Pruning had to be taught one thing. Whether a record failed is a property of the record, not of the projection. With the user columns pruned away nothing is converted, so nothing fails, and select __mo_error_message from t — the query that asks which records failed — answered "none". An external scan that keeps an error column now keeps every record-backed column through pruning; the scan's own ProjectList still projects only the referenced ones, so the cost falls only on queries that asked.

Where it is implemented

Two places produce the error columns, one per text format, shared by every engine that reads text — which is all of them except Parquet and Iceberg:

                    ┌──────────────── CsvReader.makeBatchRows ─────────────────┐
file / datastream ─►│ csvparser.Read ─► [JSONLINE: transJson2Lines] ─► getOneRowData │
foreign scan ──────►└──────────────────────────────────────────────────────────┘
kafka ────────────► KafkaReader.ReadBatch ─► parseOneMessage ─► getOneRowData

getOneRowData is the single conversion site: under tolerance it snapshots every vector's length, and on failure rolls back and emits the replacement row through appendErrorRow, which fills the synthesized columns through the ordinary column path so they are typed as the catalog declares them. Datastream and foreign scans need no code of their own — they read through the same CsvReader.

Line numbers live in the parser: lineNo counts newline bytes, readRecord snapshots it at the record's first content byte, and RecordLine() returns it 1-based. So a CSV record with a quoted field spanning lines 5-7 reports 5 and the next reports 8, and a record after a blank line reports its own line.

Three latent JSONLINE defects this uncovered

All predate this PR and are fixed here:

  1. The synthesized columns were matched against JSON object keys, so with the error columns projected every record — valid ones included — failed with "the table column is larger than input data column".
  2. A malformed line was glued onto the next one. A failed parse was held over in prevStr to be completed by the following line, and bytejson reports a bare word (this is not json) as an unexpected EOF exactly as it reports a truncated object. Text is now held over only when the parser ran off the end and the text opens the expected value; anything else is a malformed record and says so. Text held over that the file never completes is reported at EOF rather than dropped.
  3. The batch tail was trimmed by one row on every held-over record. That compensated for rows being written into pre-allocated slots, which is how the reader worked in 2023 (support load local #7493); rows are appended now, so the trim silently discarded a complete row.

Not covered

  • Parquet and Iceberg decode typed columnar values, not text: there is no line and no per-record text. Naming an error column on such a table is refused at bind time (column __mo_error_message not found), since those readers resolve columns against the file's own schema; ordinary reads and select * are unaffected. The BVT pins this boundary.
  • Constraint violations at the destination. Error mode reports what the scan could not parse; an insert ... select that violates a primary key still fails the statement.
  • A record too damaged to delimit. Tolerance is per record, and a record is whatever the CSV parser delimits — an unbalanced quote swallows the rest of the file into one record, reported as one failure.

Design notes: docs/design/external_table_error_mode.md.

Tests

Level What it proves
pkg/sql/util/csvparser TestRecordLine one record per line, a multi-line quoted record reporting its first line, exactness across a small read block, blank lines still counted
pkg/sql/colexec/external error_mode_test.go the switch (error columns tolerate, __mo_file_line alone does not, a lookalike user column does not), a pruned scan failing exactly as before, and CSV / JSONLINE / Kafka each reporting a bad record with its position, message and source text while neighbouring records are unaffected
pkg/sql/plan TestExternalScanTolerates the pruning rule is driven by the two error columns only, keyed on column id
BVT table/external_table_error_mode end to end: hidden from select */desc/show create table, the same bad record found regardless of which user columns are projected, the good/rejects split loaded into real tables, multi-line records, blank lines, an unterminated object, the parquet boundary, and the reserved names refused by DDL

Local validation: pkg/catalog, pkg/sql/colexec/external, pkg/sql/util/csvparser green; pkg/sql/plan green apart from TestBuildCreateOrReplaceViewRejectsRecursiveDefinition/future_AS_OF_timestamp, which reproduces on a clean origin/main worktree (timezone-dependent, unrelated). BVT: error-mode 45/45, load_data 1032/1032, datastream 111/111.

fengttt and others added 10 commits August 24, 2026 20:44
…#27517)

Append __mo_file_line / __mo_error_message / __mo_error_text to the TableDef
of every text-format external scan (file, Kafka, datastream, foreign), which
are the engines whose records go through the shared CSV/JSONL parsing;
Parquet/Iceberg/Mongo have their own typed readers and are excluded. For a
foreign table they are inserted before __mo_query, which must stay last.

They are hidden from SELECT * at both expansion sites, exactly like the Kafka
metadata columns, and are already rejected at CREATE/ALTER by
IsReservedExternalColName.
__mo_file_line must report the physical line a record starts on, and for a
record whose quoted field spans several lines, its FIRST line. The parser
tracked only a byte offset, which cannot answer that.

Every byte the parser consumes passes through readByte, skipBytes or
readUntil, so counting newlines at those three sites is exact; readRecord
snapshots the counter as the record's start line and RecordLine() exposes it
1-based. Tested for one-record-per-line, a quoted field spanning lines (next
record correctly reports line 4, not 2), and a deliberately tiny read block
so the bulk refill path in readUntil is exercised rather than only the
byte-at-a-time path.
…rity count (matrixorigin#27517)

- ExternalErrorMode on the scan params resolves ONCE in Prepare from the
  pruned attribute list: Tolerate is set only when __mo_error_message or
  __mo_error_text survived, and deliberately NOT by __mo_file_line alone,
  since asking for a line number must not change whether a bad record fails
  the query. A scan that mentions none of them pays one bool test.
- getFieldFromLine synthesizes all three columns instead of reading them from
  the record: __mo_file_line from the parser's record start line, and both
  error columns NULL for a record that parsed.
- The CSV loop refreshes the record line per record, so a multi-line quoted
  field reports its FIRST line.
- getRealAttrCnt must not count synthesized columns as record fields, or
  selecting one makes every row look short ("the data of row 1 contained is
  less than input columns"). __mo_filepath was already excluded by name; the
  error columns are excluded ColId-scoped, so a pre-existing table with a
  same-named real column keeps reading its own data.

Verified on a server build: SELECT * is unchanged; the columns are selectable
and NULL on good rows; a record spanning lines 1-3 reports 1 and the next
reports 4; and a file with a bad value still fails exactly as before both when
no error column is requested and when only __mo_file_line is.

Per-row tolerance (emitting the error row instead of failing) is the next
commit; requesting the error columns currently still fails.
)

When the query keeps __mo_error_message or __mo_error_text, a record that
cannot be materialized no longer fails the statement: the row is emitted with
every user column NULL, __mo_filepath and __mo_file_line as usual, the reason
in __mo_error_message and the failed record in __mo_error_text.

Columns are appended one at a time, so a failure part-way through a record
leaves the batch's vectors at unequal lengths. The tolerant path snapshots
their lengths before the record and truncates back to them before emitting the
replacement row -- the same rollback the MongoDB reader already uses. The
snapshot buffer is reused across rows, so tolerance costs no per-record
allocation, and the whole path is behind one bool resolved in Prepare.

Every user column of a failed record is NULL, including columns that happened
to convert before the failure: a record that did not parse has no trustworthy
value for any of them.

__mo_error_text is rebuilt by re-joining the parser's decoded fields with the
configured terminator, so quoting and escaping are normalized rather than
byte-identical to the file.

Verified on a server build over a file with two bad rows among five:
- no error column requested        -> fails exactly as before
- error columns requested          -> 5 rows, bad ones NULL with line 2 and 4,
                                      their messages, and "b,notanint" /
                                      "d,alsobad" as the failed text
- only __mo_error_text requested   -> also tolerated
- count(*)/count(b)/count(error)   -> 5 / 3 / 2
A JSONLINE record now reports its own failure through the error-mode
columns instead of failing the whole scan, and three latent defects in
that path had to be closed for it to be correct:

- The synthesized error columns were matched against JSON object keys and
  counted as expected fields, so every record -- valid ones included --
  failed with "the table column is larger than input data column".
- A parse failure held the line over in prevStr to be completed by the
  next line. bytejson reports a bare word ("this is not json") as an
  unexpected EOF just like a truncated object, so a malformed line was
  glued onto the following one, corrupting it. The text is now held over
  only when the parser ran off the end AND the text opens the expected
  value; anything else is a malformed record and says so. Text held over
  that the file never completes is reported rather than dropped.
- The batch tail was trimmed by one row whenever a record was held over.
  That compensated for rows being written into pre-allocated slots (2023);
  rows are appended now, so it silently discarded a complete row.

__mo_error_text carries the source line for JSONLINE rather than the
decoded fields re-joined with a comma, and the csv parser now takes a
record's start line at its first content byte, so a record following a
blank line reports its true physical line.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6
A Kafka message whose value does not parse now becomes a reported record
instead of failing the scan, like a bad line in a file. Two things follow
from a message not being a line:

- __mo_file_line is NULL for a Kafka scan. A message has no line in a
  file; __mo_message_id is what locates it, so the error row carries the
  offset and the reader keeps reading.
- A failed row keeps every column the scan synthesizes -- __mo_filepath,
  __mo_file_line, the Kafka metadata columns -- and NULLs only the user
  columns, which are the ones the record failed to supply. appendErrorRow
  fills them through the ordinary column path rather than by hand, so
  they are typed as the catalog declares them.

Datastream (jstfu) needs no work of its own: it reads through the same
CSV reader, so its __mo_file_line is the line count of the run, as asked
for in the issue.

Tests cover what the issue specifies: tolerance is switched on by the
error columns alone (asking only for __mo_file_line still fails the
query), a pruned scan behaves exactly as before, and CSV, JSONLINE and
Kafka each report a bad record with its position, message and source
text while the records around it are unaffected.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6
…gn doc

Whether an external record failed to parse is a property of the record,
not of the query. Column pruning broke that: with the user columns pruned
away nothing is converted, so nothing fails, and the two queries the
feature exists for

  select __mo_error_message from t;
  select __mo_file_line, __mo_error_text from t where __mo_error_message is not null;

both answered "none" -- while `select s, __mo_error_message from t`
returned the bad record's other column as though it had parsed.

An external scan that keeps __mo_error_message or __mo_error_text now
keeps every record-backed column through pruning. The scan's ProjectList
still projects only the referenced ones, so the extra columns occupy a
batch vector and go no further, and the cost is paid only by a query that
asked for the error columns. Synthetic and hidden columns are pruned as
before: they are not read from the record, so they cannot fail.

BVT covers CSV and JSONLINE end to end: hidden from select * / desc /
show create table, the same bad record found regardless of which user
columns are projected, the good/rejects split loaded into real tables,
multi-line records, blank lines, an unterminated object, and the reserved
names refused by DDL. 42/42 green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6
Parquet-backed external tables decode typed columnar values, so the
error-mode columns have nothing to report there. Verified what actually
happens rather than assuming: ordinary reads and `select *` are
unaffected, and naming an error column is refused at bind time with
`column __mo_error_message not found`, because the parquet reader
resolves columns against the file's own schema. The BVT now pins that,
and the design doc states it instead of implying the columns are simply
always NULL there.

Foreign-table scans need no work of their own: ForeignScanReader.ReadBatch
delegates to the same CsvReader.makeBatchRows as file and datastream
scans, so tolerance, __mo_file_line and the error columns come through
the shared path.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6
@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 →

Writing the load these columns exist for, over sources that fail in many
ways at once. `errmix.csv` and `errmix.jsonl` carry ten records: a good
one, a non-numeric int, a non-numeric decimal, an unparsable timestamp,
too few fields, too many fields, an out-of-range int, an embedded quote,
an impossible date (2024-02-30), a line that is not JSON at all, and a
truncated object.

BVT `external_table_error_mode_load` does the real thing in one
statement: multi-table INSERT sends the good records to a destination
table and every bad one to a rejects table (line, message, text), and the
statement does not fail. It asserts every source record is accounted for
exactly once, that INSERT ALL routes a row to every branch it satisfies
(an always-true audit branch receives all ten), and that the same load
with the error columns pruned still fails on the first bad record.

On Kafka the same split runs against a REAL broker in the e2e harness
(optools/kafka_ci.bash), over 8 malformed messages: rejects carry
__mo_message_id and the message value as published, __mo_file_line is
NULL because a message has no line in a file, and a read without the
error columns still fails. It is a separate scenario rather than part of
run(), because run() is also driven by the broker-free unit test against
a SQL simulator, and teaching that simulator to model multi-table INSERT
would make it the oracle for a feature it does not implement. Verified:
the harness reports all four new cases passing alongside the nine
existing ones.

Two things the fixtures taught, both now fixed or documented:

- A truncated JSON object was held over to be completed by the following
  lines, so one bad line swallowed every good record after it and
  reported a single failure at EOF. Under tolerance it is now that line's
  own failure and the scan resumes at the next line. This costs nothing:
  a continuation line that starts with a quote makes the CSV splitter
  fail the whole scan, so multi-line objects are not readable anyway.
  Non-tolerant scans keep the old behaviour.
- An unbalanced quote leaves the parser with no record boundary and fails
  the scan outright; tolerance cannot catch it because there is no record
  to attribute it to. The design doc said such a record was "reported as
  one failure", which was wrong.

Also of note, recorded by the goldens: a file external table accepts a
record with too MANY fields and ignores the extra (external.go's
`len(line) < realAttrCnt` rule), while Kafka rejects it -- the two take
different branches of checkLineValidRestrictive.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6
Conflict in test/kafkaexttab/kafka_e2e_local_test.go with matrixorigin#27593
(fix(kafka): use explicit transaction checkpoints), which reworked the
simulator's transaction bookkeeping while this branch added error-mode
cases to the same two switches. Both sides are additive: upstream's
ROLLBACK line now clears pendCheckpointSet instead of pendLastSet, and
its kafka_checkpoint query case sits alongside the error-mode cases.
Taken as such, with upstream's rewritten line kept.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6
@fengttt
fengttt merged commit 3a3a801 into matrixorigin:main Aug 27, 2026
2 of 5 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]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…ssage / __mo_error_text (matrixorigin#27517) (matrixorigin#27609)

## 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 matrixorigin#27517

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

A scan of an external table fails the whole statement on the first
record it cannot parse. One bad line in a million-line file means no
result at all, and no way to find out which line it was without reading
the file by hand.

This adds an **error mode**: a bad record becomes a *row* instead of a
*failure*. It is switched on by asking for it — by selecting one of two
columns the query would otherwise not mention.

### The columns

Three hidden columns exist on every text-backed external table
(`EXTERNAL`, `KAFKA`, `DATASTREAM`, foreign). They do not appear in
`select *`, `desc`, or `show create table`, and their names are reserved
so a user table cannot declare them.

| Column | Type | Meaning |
|---|---|---|
| `__mo_file_line` | `bigint` | the physical line the record starts on
(`NULL` for Kafka, which has no lines) |
| `__mo_error_message` | `varchar` | why the record failed, `NULL` if it
parsed |
| `__mo_error_text` | `varchar` | the record as written in the source,
`NULL` if it parsed |

```sql
create external table t (a int, s varchar(20))
  infile{'filepath'='/data/rows.csv'};

-- unchanged: fails on the first bad record
select * from t;

-- reports them instead
select a, s, __mo_file_line, __mo_error_message, __mo_error_text from t;

-- the two halves of a load
insert into good    select a, s from t where __mo_error_message is null;
insert into rejects select __mo_file_line, __mo_error_message, __mo_error_text from t
                    where __mo_error_message is not null;
```

On a failed row every user column is `NULL` — including one that
happened to convert before the failure, because the record is not
trustworthy — while every column the scan *synthesizes* keeps its value:
`__mo_filepath`, `__mo_file_line`, and the Kafka metadata columns. Those
are what let a user find the record again.

### What switches it on

`__mo_error_message` and `__mo_error_text` turn tolerance on.
`__mo_file_line` deliberately does **not**: it is position metadata, and
per the issue a query that only wants line numbers must still fail on a
bad record. The decision is made once per scan in
`resolveExternalErrorMode`, from the attribute list the operator was
given — column pruning has already run, so a query that does not mention
the columns takes the historical path with no per-row test to pay for.
It is keyed on the reserved column ids, not the names.

**Pruning had to be taught one thing.** Whether a record failed is a
property of the record, not of the projection. With the user columns
pruned away nothing is converted, so nothing fails, and `select
__mo_error_message from t` — the query that asks which records failed —
answered "none". An external scan that keeps an error column now keeps
every record-backed column through pruning; the scan's own `ProjectList`
still projects only the referenced ones, so the cost falls only on
queries that asked.

### Where it is implemented

Two places produce the error columns, one per text format, shared by
every engine that reads text — which is all of them except Parquet and
Iceberg:

```
                    ┌──────────────── CsvReader.makeBatchRows ─────────────────┐
file / datastream ─►│ csvparser.Read ─► [JSONLINE: transJson2Lines] ─► getOneRowData │
foreign scan ──────►└──────────────────────────────────────────────────────────┘
kafka ────────────► KafkaReader.ReadBatch ─► parseOneMessage ─► getOneRowData
```

`getOneRowData` is the single conversion site: under tolerance it
snapshots every vector's length, and on failure rolls back and emits the
replacement row through `appendErrorRow`, which fills the synthesized
columns through the ordinary column path so they are typed as the
catalog declares them. Datastream and foreign scans need no code of
their own — they read through the same `CsvReader`.

Line numbers live in the parser: `lineNo` counts newline bytes,
`readRecord` snapshots it at the record's **first content byte**, and
`RecordLine()` returns it 1-based. So a CSV record with a quoted field
spanning lines 5-7 reports 5 and the next reports 8, and a record after
a blank line reports its own line.

### Three latent JSONLINE defects this uncovered

All predate this PR and are fixed here:

1. **The synthesized columns were matched against JSON object keys**, so
with the error columns projected *every* record — valid ones included —
failed with "the table column is larger than input data column".
2. **A malformed line was glued onto the next one.** A failed parse was
held over in `prevStr` to be completed by the following line, and
`bytejson` reports a bare word (`this is not json`) as an unexpected EOF
exactly as it reports a truncated object. Text is now held over only
when the parser ran off the end *and* the text opens the expected value;
anything else is a malformed record and says so. Text held over that the
file never completes is reported at EOF rather than dropped.
3. **The batch tail was trimmed by one row on every held-over record.**
That compensated for rows being written into pre-allocated slots, which
is how the reader worked in 2023 (matrixorigin#7493); rows are appended now, so the
trim silently discarded a complete row.

### Not covered

- **Parquet and Iceberg** decode typed columnar values, not text: there
is no line and no per-record text. Naming an error column on such a
table is refused at bind time (`column __mo_error_message not found`),
since those readers resolve columns against the file's own schema;
ordinary reads and `select *` are unaffected. The BVT pins this
boundary.
- **Constraint violations at the destination.** Error mode reports what
the *scan* could not parse; an `insert ... select` that violates a
primary key still fails the statement.
- **A record too damaged to delimit.** Tolerance is per record, and a
record is whatever the CSV parser delimits — an unbalanced quote
swallows the rest of the file into one record, reported as one failure.

Design notes: `docs/design/external_table_error_mode.md`.

## Tests

| Level | What it proves |
|---|---|
| `pkg/sql/util/csvparser` `TestRecordLine` | one record per line, a
multi-line quoted record reporting its first line, exactness across a
small read block, blank lines still counted |
| `pkg/sql/colexec/external` `error_mode_test.go` | the switch (error
columns tolerate, `__mo_file_line` alone does not, a lookalike user
column does not), a pruned scan failing exactly as before, and CSV /
JSONLINE / Kafka each reporting a bad record with its position, message
and source text while neighbouring records are unaffected |
| `pkg/sql/plan` `TestExternalScanTolerates` | the pruning rule is
driven by the two error columns only, keyed on column id |
| BVT `table/external_table_error_mode` | end to end: hidden from
`select *`/`desc`/`show create table`, the same bad record found
regardless of which user columns are projected, the good/rejects split
loaded into real tables, multi-line records, blank lines, an
unterminated object, the parquet boundary, and the reserved names
refused by DDL |

Local validation: `pkg/catalog`, `pkg/sql/colexec/external`,
`pkg/sql/util/csvparser` green; `pkg/sql/plan` green apart from
`TestBuildCreateOrReplaceViewRejectsRecursiveDefinition/future_AS_OF_timestamp`,
which reproduces on a clean `origin/main` worktree (timezone-dependent,
unrelated). BVT: error-mode 45/45, `load_data` 1032/1032, `datastream`
111/111.

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…ssage / __mo_error_text (matrixorigin#27517) (matrixorigin#27609)

## 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 matrixorigin#27517

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

A scan of an external table fails the whole statement on the first
record it cannot parse. One bad line in a million-line file means no
result at all, and no way to find out which line it was without reading
the file by hand.

This adds an **error mode**: a bad record becomes a *row* instead of a
*failure*. It is switched on by asking for it — by selecting one of two
columns the query would otherwise not mention.

### The columns

Three hidden columns exist on every text-backed external table
(`EXTERNAL`, `KAFKA`, `DATASTREAM`, foreign). They do not appear in
`select *`, `desc`, or `show create table`, and their names are reserved
so a user table cannot declare them.

| Column | Type | Meaning |
|---|---|---|
| `__mo_file_line` | `bigint` | the physical line the record starts on
(`NULL` for Kafka, which has no lines) |
| `__mo_error_message` | `varchar` | why the record failed, `NULL` if it
parsed |
| `__mo_error_text` | `varchar` | the record as written in the source,
`NULL` if it parsed |

```sql
create external table t (a int, s varchar(20))
  infile{'filepath'='/data/rows.csv'};

-- unchanged: fails on the first bad record
select * from t;

-- reports them instead
select a, s, __mo_file_line, __mo_error_message, __mo_error_text from t;

-- the two halves of a load
insert into good    select a, s from t where __mo_error_message is null;
insert into rejects select __mo_file_line, __mo_error_message, __mo_error_text from t
                    where __mo_error_message is not null;
```

On a failed row every user column is `NULL` — including one that
happened to convert before the failure, because the record is not
trustworthy — while every column the scan *synthesizes* keeps its value:
`__mo_filepath`, `__mo_file_line`, and the Kafka metadata columns. Those
are what let a user find the record again.

### What switches it on

`__mo_error_message` and `__mo_error_text` turn tolerance on.
`__mo_file_line` deliberately does **not**: it is position metadata, and
per the issue a query that only wants line numbers must still fail on a
bad record. The decision is made once per scan in
`resolveExternalErrorMode`, from the attribute list the operator was
given — column pruning has already run, so a query that does not mention
the columns takes the historical path with no per-row test to pay for.
It is keyed on the reserved column ids, not the names.

**Pruning had to be taught one thing.** Whether a record failed is a
property of the record, not of the projection. With the user columns
pruned away nothing is converted, so nothing fails, and `select
__mo_error_message from t` — the query that asks which records failed —
answered "none". An external scan that keeps an error column now keeps
every record-backed column through pruning; the scan's own `ProjectList`
still projects only the referenced ones, so the cost falls only on
queries that asked.

### Where it is implemented

Two places produce the error columns, one per text format, shared by
every engine that reads text — which is all of them except Parquet and
Iceberg:

```
                    ┌──────────────── CsvReader.makeBatchRows ─────────────────┐
file / datastream ─►│ csvparser.Read ─► [JSONLINE: transJson2Lines] ─► getOneRowData │
foreign scan ──────►└──────────────────────────────────────────────────────────┘
kafka ────────────► KafkaReader.ReadBatch ─► parseOneMessage ─► getOneRowData
```

`getOneRowData` is the single conversion site: under tolerance it
snapshots every vector's length, and on failure rolls back and emits the
replacement row through `appendErrorRow`, which fills the synthesized
columns through the ordinary column path so they are typed as the
catalog declares them. Datastream and foreign scans need no code of
their own — they read through the same `CsvReader`.

Line numbers live in the parser: `lineNo` counts newline bytes,
`readRecord` snapshots it at the record's **first content byte**, and
`RecordLine()` returns it 1-based. So a CSV record with a quoted field
spanning lines 5-7 reports 5 and the next reports 8, and a record after
a blank line reports its own line.

### Three latent JSONLINE defects this uncovered

All predate this PR and are fixed here:

1. **The synthesized columns were matched against JSON object keys**, so
with the error columns projected *every* record — valid ones included —
failed with "the table column is larger than input data column".
2. **A malformed line was glued onto the next one.** A failed parse was
held over in `prevStr` to be completed by the following line, and
`bytejson` reports a bare word (`this is not json`) as an unexpected EOF
exactly as it reports a truncated object. Text is now held over only
when the parser ran off the end *and* the text opens the expected value;
anything else is a malformed record and says so. Text held over that the
file never completes is reported at EOF rather than dropped.
3. **The batch tail was trimmed by one row on every held-over record.**
That compensated for rows being written into pre-allocated slots, which
is how the reader worked in 2023 (matrixorigin#7493); rows are appended now, so the
trim silently discarded a complete row.

### Not covered

- **Parquet and Iceberg** decode typed columnar values, not text: there
is no line and no per-record text. Naming an error column on such a
table is refused at bind time (`column __mo_error_message not found`),
since those readers resolve columns against the file's own schema;
ordinary reads and `select *` are unaffected. The BVT pins this
boundary.
- **Constraint violations at the destination.** Error mode reports what
the *scan* could not parse; an `insert ... select` that violates a
primary key still fails the statement.
- **A record too damaged to delimit.** Tolerance is per record, and a
record is whatever the CSV parser delimits — an unbalanced quote
swallows the rest of the file into one record, reported as one failure.

Design notes: `docs/design/external_table_error_mode.md`.

## Tests

| Level | What it proves |
|---|---|
| `pkg/sql/util/csvparser` `TestRecordLine` | one record per line, a
multi-line quoted record reporting its first line, exactness across a
small read block, blank lines still counted |
| `pkg/sql/colexec/external` `error_mode_test.go` | the switch (error
columns tolerate, `__mo_file_line` alone does not, a lookalike user
column does not), a pruned scan failing exactly as before, and CSV /
JSONLINE / Kafka each reporting a bad record with its position, message
and source text while neighbouring records are unaffected |
| `pkg/sql/plan` `TestExternalScanTolerates` | the pruning rule is
driven by the two error columns only, keyed on column id |
| BVT `table/external_table_error_mode` | end to end: hidden from
`select *`/`desc`/`show create table`, the same bad record found
regardless of which user columns are projected, the good/rejects split
loaded into real tables, multi-line records, blank lines, an
unterminated object, the parquet boundary, and the reserved names
refused by DDL |

Local validation: `pkg/catalog`, `pkg/sql/colexec/external`,
`pkg/sql/util/csvparser` green; `pkg/sql/plan` green apart from
`TestBuildCreateOrReplaceViewRejectsRecursiveDefinition/future_AS_OF_timestamp`,
which reproduces on a clean `origin/main` worktree (timezone-dependent,
unrelated). BVT: error-mode 45/45, `load_data` 1032/1032, `datastream`
111/111.

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…ssage / __mo_error_text (matrixorigin#27517) (matrixorigin#27609)

## 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 matrixorigin#27517

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

A scan of an external table fails the whole statement on the first
record it cannot parse. One bad line in a million-line file means no
result at all, and no way to find out which line it was without reading
the file by hand.

This adds an **error mode**: a bad record becomes a *row* instead of a
*failure*. It is switched on by asking for it — by selecting one of two
columns the query would otherwise not mention.

### The columns

Three hidden columns exist on every text-backed external table
(`EXTERNAL`, `KAFKA`, `DATASTREAM`, foreign). They do not appear in
`select *`, `desc`, or `show create table`, and their names are reserved
so a user table cannot declare them.

| Column | Type | Meaning |
|---|---|---|
| `__mo_file_line` | `bigint` | the physical line the record starts on
(`NULL` for Kafka, which has no lines) |
| `__mo_error_message` | `varchar` | why the record failed, `NULL` if it
parsed |
| `__mo_error_text` | `varchar` | the record as written in the source,
`NULL` if it parsed |

```sql
create external table t (a int, s varchar(20))
  infile{'filepath'='/data/rows.csv'};

-- unchanged: fails on the first bad record
select * from t;

-- reports them instead
select a, s, __mo_file_line, __mo_error_message, __mo_error_text from t;

-- the two halves of a load
insert into good    select a, s from t where __mo_error_message is null;
insert into rejects select __mo_file_line, __mo_error_message, __mo_error_text from t
                    where __mo_error_message is not null;
```

On a failed row every user column is `NULL` — including one that
happened to convert before the failure, because the record is not
trustworthy — while every column the scan *synthesizes* keeps its value:
`__mo_filepath`, `__mo_file_line`, and the Kafka metadata columns. Those
are what let a user find the record again.

### What switches it on

`__mo_error_message` and `__mo_error_text` turn tolerance on.
`__mo_file_line` deliberately does **not**: it is position metadata, and
per the issue a query that only wants line numbers must still fail on a
bad record. The decision is made once per scan in
`resolveExternalErrorMode`, from the attribute list the operator was
given — column pruning has already run, so a query that does not mention
the columns takes the historical path with no per-row test to pay for.
It is keyed on the reserved column ids, not the names.

**Pruning had to be taught one thing.** Whether a record failed is a
property of the record, not of the projection. With the user columns
pruned away nothing is converted, so nothing fails, and `select
__mo_error_message from t` — the query that asks which records failed —
answered "none". An external scan that keeps an error column now keeps
every record-backed column through pruning; the scan's own `ProjectList`
still projects only the referenced ones, so the cost falls only on
queries that asked.

### Where it is implemented

Two places produce the error columns, one per text format, shared by
every engine that reads text — which is all of them except Parquet and
Iceberg:

```
                    ┌──────────────── CsvReader.makeBatchRows ─────────────────┐
file / datastream ─►│ csvparser.Read ─► [JSONLINE: transJson2Lines] ─► getOneRowData │
foreign scan ──────►└──────────────────────────────────────────────────────────┘
kafka ────────────► KafkaReader.ReadBatch ─► parseOneMessage ─► getOneRowData
```

`getOneRowData` is the single conversion site: under tolerance it
snapshots every vector's length, and on failure rolls back and emits the
replacement row through `appendErrorRow`, which fills the synthesized
columns through the ordinary column path so they are typed as the
catalog declares them. Datastream and foreign scans need no code of
their own — they read through the same `CsvReader`.

Line numbers live in the parser: `lineNo` counts newline bytes,
`readRecord` snapshots it at the record's **first content byte**, and
`RecordLine()` returns it 1-based. So a CSV record with a quoted field
spanning lines 5-7 reports 5 and the next reports 8, and a record after
a blank line reports its own line.

### Three latent JSONLINE defects this uncovered

All predate this PR and are fixed here:

1. **The synthesized columns were matched against JSON object keys**, so
with the error columns projected *every* record — valid ones included —
failed with "the table column is larger than input data column".
2. **A malformed line was glued onto the next one.** A failed parse was
held over in `prevStr` to be completed by the following line, and
`bytejson` reports a bare word (`this is not json`) as an unexpected EOF
exactly as it reports a truncated object. Text is now held over only
when the parser ran off the end *and* the text opens the expected value;
anything else is a malformed record and says so. Text held over that the
file never completes is reported at EOF rather than dropped.
3. **The batch tail was trimmed by one row on every held-over record.**
That compensated for rows being written into pre-allocated slots, which
is how the reader worked in 2023 (matrixorigin#7493); rows are appended now, so the
trim silently discarded a complete row.

### Not covered

- **Parquet and Iceberg** decode typed columnar values, not text: there
is no line and no per-record text. Naming an error column on such a
table is refused at bind time (`column __mo_error_message not found`),
since those readers resolve columns against the file's own schema;
ordinary reads and `select *` are unaffected. The BVT pins this
boundary.
- **Constraint violations at the destination.** Error mode reports what
the *scan* could not parse; an `insert ... select` that violates a
primary key still fails the statement.
- **A record too damaged to delimit.** Tolerance is per record, and a
record is whatever the CSV parser delimits — an unbalanced quote
swallows the rest of the file into one record, reported as one failure.

Design notes: `docs/design/external_table_error_mode.md`.

## Tests

| Level | What it proves |
|---|---|
| `pkg/sql/util/csvparser` `TestRecordLine` | one record per line, a
multi-line quoted record reporting its first line, exactness across a
small read block, blank lines still counted |
| `pkg/sql/colexec/external` `error_mode_test.go` | the switch (error
columns tolerate, `__mo_file_line` alone does not, a lookalike user
column does not), a pruned scan failing exactly as before, and CSV /
JSONLINE / Kafka each reporting a bad record with its position, message
and source text while neighbouring records are unaffected |
| `pkg/sql/plan` `TestExternalScanTolerates` | the pruning rule is
driven by the two error columns only, keyed on column id |
| BVT `table/external_table_error_mode` | end to end: hidden from
`select *`/`desc`/`show create table`, the same bad record found
regardless of which user columns are projected, the good/rejects split
loaded into real tables, multi-line records, blank lines, an
unterminated object, the parquet boundary, and the reserved names
refused by DDL |

Local validation: `pkg/catalog`, `pkg/sql/colexec/external`,
`pkg/sql/util/csvparser` green; `pkg/sql/plan` green apart from
`TestBuildCreateOrReplaceViewRejectsRecursiveDefinition/future_AS_OF_timestamp`,
which reproduces on a clean `origin/main` worktree (timezone-dependent,
unrelated). BVT: error-mode 45/45, `load_data` 1032/1032, `datastream`
111/111.

---------

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/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants