Skip to content

Explain data/expected structure mismatches in INSERT parse errors - #110626

Open
alexey-milovidov wants to merge 195 commits into
masterfrom
insert-schema-mismatch-diagnostic
Open

alexey-milovidov wants to merge 195 commits into
masterfrom
insert-schema-mismatch-diagnostic

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 15, 2026 •

Copy link
Copy Markdown
Member

Improves the error message shown when parsing the data of an INSERT fails.

Previously, inserting data whose structure does not match the destination produced a confusing low-level parse error (for example Cannot parse input: expected '\t' before ...) with no hint about the real cause. In the linked issue, the destination's inferred schema had integer columns while the inserted TSV data had string columns, and the reported error pointed at a tab that was actually present.

Now, on a parse failure, ClickHouse infers the structure of the data being inserted (only when the format has a data schema reader, and solely for diagnostics) and, if it does not correspond to the expected structure, appends an explanation listing both the inferred and the expected structure. For example:

Code: 27. DB::Exception: Cannot parse input: expected '\t' before: 'page_view...
...
The structure of the data being inserted does not match the structure expected by the query, which is likely the cause of the parsing error.
Inferred structure of the input data (in format `TSV`):
    c1 Nullable(Int64)
    c2 Nullable(String)
    c3 Nullable(String)
Expected structure:
    c1 Int64
    c2 Int64
    c3 Int64

The check is wired through a lazy provider on IInputFormat that runs only on a genuine parse error, so there is no cost on the happy path. The comparison ignores the artificial Nullable wrapper that schema inference adds by default, so inserting valid data into non-nullable columns is not falsely flagged. It covers the synchronous local/server path, client-side parsing, and the asynchronous insert queue (the default path now that async_insert is enabled by default).

Closes: #110622

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

When parsing of the data being inserted by an INSERT fails, the error message now explains a likely structure mismatch by comparing the structure inferred from the data with the structure expected by the query.


Workflow [PR]
Sync PR [sync-upstream/pr/110626]

When parsing the data of an INSERT fails and the data does not match the
structure expected by the query (a common and confusing situation, e.g.
inserting `TSV` data with string columns into a destination whose inferred
schema has integer columns), the error message is cryptic.

On such a failure, and only for diagnostics, infer the structure of the
data being inserted (when the format has a data schema reader) and, if it
does not correspond to the expected structure, append an explanation
listing both the inferred and the expected structure.

This is wired through a lazy provider on `IInputFormat` that runs only on a
genuine parse error, so there is no cost on the happy path. It covers the
synchronous local/server path, client-side parsing, and the asynchronous
insert queue.

Closes: #110622

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3d3c0ea]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb

AI Review

Summary

The PR adds inferred-schema explanations to INSERT parsing errors across server, client, and asynchronous insert paths. Reviewed head 3d3c0ea54d4992319d208c0e397ca3fc06e0fb07 and all prior discussion. Two Majors remain: one new misleading CSV explanation and the previously reported exception-preservation gap in FROM INFILE.

Findings

⚠️ Majors

  • getSourceFromASTInsertQuery.cpp:1651–1653: Replay loses empty-field default semantics. With destination (a UInt8, n UInt8), header detection disabled, input_format_csv_missing_nullable_as_empty_string=1, and default input_format_csv_empty_as_default=1, CSV input ,1.5\n fails only on n; the empty a correctly defaults to zero. Inference replaces the empty field with Nullable(String), replay preserves it as "", and the numeric probes reject that string, inventing a structure mismatch. The same problem occurs with non-nullable inference. Preserve empty/default provenance at replay, or leave these comparisons inconclusive. Posted as one new inline finding.
  • ClientBase.cpp:2945: Attaching the optional file explanation can replace the original exception. e.addMessage(description) remains outside a protective guard after the file helper returns; allocation failure while copying, masking, or appending the explanation escapes instead of rethrowing the parse exception. Protect preparation and attachment together, as IInputFormat::generate now does. Already covered by the existing unresolved thread; no duplicate comment or reply posted.
Tests
  • ⚠️ Add the CSV empty-field case above with a successful ,1\n control, covering nullable and non-nullable inference. Add attachment-failure coverage through INSERT ... FROM INFILE; the existing failpoint test exercises IInputFormat.
  • The CI report reports 15,497 passed tests, 4,606 skipped, and no failures. Both findings are established by current source traces; no tests were executed locally because this review job has no ClickHouse binary.
Final Verdict

Status: ⚠️ Request changes

Preserve format-specific empty-field defaults in diagnostic evidence, and guard optional explanation attachment on the FROM INFILE path, with the focused regressions above.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 15, 2026
alexey-milovidov and others added 2 commits July 16, 2026 00:11
The diagnostic already works over the HTTP interface (the handler
concatenates the URL query with the request body, so the inserted data is
inline and re-readable, and the asynchronous insert path covers it too).
Add explicit HTTP test cases (synchronous and asynchronous) to lock in the
behaviour.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The style check flags a catch-all that does not rethrow/log unless it
carries a comment containing the word 'Ok'. The block is intentionally a
best-effort diagnostic that ignores failures, so annotate it accordingly.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Client/ClientBase.cpp Resolved
alexey-milovidov and others added 2 commits July 16, 2026 10:34
`ClientBase::sendDataFrom` wired the parse-error diagnostic added in the
previous commits via `setInsertSchemaMismatchDiagnostic`, which re-reads
`ASTInsertQuery::data`. That is null when the query text comes from
`--query` and the data is piped in separately via stdin (e.g.
`clickhouse-client --query "INSERT ... FORMAT TSV" < data.tsv`), so this
common case silently fell back to the old, unexplained parse error.

Add `PrefixCapturingReadBuffer`, a `ReadBuffer` decorator that captures a
bounded prefix of the bytes read through it (capped by
`input_format_max_bytes_to_read_for_schema_inference`, so it samples no
more than schema inference itself would). `sendDataFrom` now uses it
whenever the data is not inline in the query text, and feeds the captured
prefix to the existing `getInsertDataSchemaMismatchDescription`. The
inline-data path is untouched and stays free of the extra copy.

AI review finding on #110626.
…uffer

`IInputFormat::generate` looks up the file name of its read buffer via
`getFileNameFromReadBuffer` to add the `(in file/uri ...)` part to error
messages. `PrefixCapturingReadBuffer` did not implement
`ReadBufferWrapperBase`, so wrapping the client's stdin buffer hid the
underlying buffer's file name and dropped `(in file/uri (fd = 0))` from
the message, breaking `03533_column_array_insert_broken_offsets` in the
Fast test:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110626&sha=cbd1b7d327fe0b4b1b1c1ac9948eda02cc07bc29&name_0=PR&name_1=Fast%20test
#110626

Implement `ReadBufferWrapperBase` (the same idiom as `ReadBufferWrapper`
and `CompressedReadBufferWrapper`) so the lookup sees through the wrapper.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Client/ClientBase.cpp Resolved
alexey-milovidov and others added 3 commits July 17, 2026 04:33
…tch-diagnostic

# Conflicts:
#	src/Processors/Transforms/getSourceFromASTInsertQuery.h
Addresses review feedback: `ClientBase::sendDataFrom` derived `data_is_inline`
from `ASTInsertQuery::data`, which stays non-null even when the buffer being
parsed by a particular call comes from stdin. When an `INSERT` given via
`--query` carries an inline data prefix and more data is streamed from stdin,
the client parses the inline prefix first and then re-enters `sendDataFrom` for
the stdin tail reusing the same `ASTInsertQuery`. A parse failure in that
streamed tail therefore re-ran the schema-mismatch diagnostic on the old inline
prefix instead of the bytes that actually failed.

The source of the data is known only to the caller, so pass `data_is_inline`
explicitly: `true` for the inline-data call, and `false` (the default) for the
stdin path, which then captures the streamed prefix via `PrefixCapturingReadBuffer`.

Adds a regression test covering the mixed inline-prefix + streamed-tail path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Addresses review feedback: the mismatch check compared type names after
stripping only the top-level `Nullable`. Schema inference deliberately widens
types (numbers become broad types such as `Int64` / `UInt64` / `Float64`) and
does not reconstruct wrappers such as `LowCardinality` or `Enum`, so exact
`getName` equality flagged a "likely structure mismatch" for inputs that are in
fact perfectly insertable (e.g. into `UInt8`, `Float32` or `LowCardinality(String)`
columns). An unrelated parse error later in the stream could then pick up a
misleading schema-mismatch suffix.

Treat a column as mismatched only when the inferred and expected types have no
common supertype at all (e.g. a `String` inferred for a numeric column) — a
strong, low-false-positive signal that the data really has a different shape
than the query expects. `tryGetLeastSupertype` also subsumes the previous
`Nullable`-stripping special case.

Adds a regression test where the destination columns are narrower/wrapped
(`UInt8`, `LowCardinality(String)`) but still compatible with the sampled input,
and the parse fails only because a fractional value cannot be read into an
integer column: no misleading explanation must be attached.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits July 17, 2026 10:00
…il test

The flaky check for `04603_insert_schema_mismatch_diagnostic_stdin_tail`
failed reproducibly (47/47) with the randomized setting
`--send_table_structure_on_insert_with_inline_data 0`.

That test exercises the mixed-source path: the `INSERT` query text carries
a valid inline data prefix and the rest is streamed from stdin. This path
requires the client to parse the inline prefix itself, which only happens
when `send_table_structure_on_insert_with_inline_data` is `1` (the default).
With it set to `0` (or `--inline-insert-data`), the client sends the inline
data to the server unparsed, and a query that has both inline data and
external stdin data is rejected up front with `NOT_IMPLEMENTED` (a
pre-existing limitation of the `inline-insert-data` mode, unrelated to this
change), so there is no client-side parse error to diagnose.

Pin the setting to `1` on the two client invocations so settings
randomization cannot switch the test onto the unsupported path. Verified
locally against a server built from this branch: with the culprit setting
injected by the harness, the pinned value wins (last-wins with
`--allow_repeated_settings`) and the test matches its reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rder formats

Addresses two AI-review findings on `getInsertDataSchemaMismatchDescription`:

1. For formats without a strict column order (`JSONEachRow`, `TSKV`),
   `readSchemaFromFormat` reorders the inferred columns to match the
   destination table, resolving it through `context->getInsertionTable` in the
   local `DatabaseCatalog`. On the `clickhouse-client` path the destination is
   a remote table that is not registered in the local catalog, so that lookup
   threw and the surrounding catch suppressed the whole diagnostic: a genuine
   `INSERT ... FORMAT JSONEachRow` structure mismatch showed only the bare
   parse error. Run schema inference with the insertion table cleared (its only
   use there is that reordering) and instead match the inferred columns against
   `expected_header` by name for such formats, falling back to a positional
   comparison for strict-order formats (`TSV`, `CSV`, `Values`), whose inferred
   names are positional placeholders like `c1`, `c2`.

2. The compatibility check was stricter than actual insertability for types
   parsed from text. `JSONEachRow` inserts JSON strings into `UUID`, `IPv4` /
   `IPv6`, `Enum`, `FixedString` and date columns, but schema inference keeps
   those fields as `String`, so an unrelated parse error (e.g. a fractional
   value for a `UInt8` column) picked up a misleading "structure mismatch"
   suffix. Treat a `String` inferred for such a destination as compatible. A
   numeric destination is deliberately excluded, preserving the reliable "text
   where a number is expected" signal this diagnostic exists to surface.

Adds `04605_insert_schema_mismatch_diagnostic_json` covering the genuine
mismatch, a reordered-columns mismatch, and the no-false-positive `UUID` case.

Verified locally against a server built from this branch.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits July 17, 2026 14:49
Addresses two follow-up review findings on the JSONEachRow / named-format
comparison path in `getInsertDataSchemaMismatchDescription`, both of which
produced a misleading "structure mismatch" suffix on an unrelated parse error.

1. The `String`-inferred compatibility whitelist was still incomplete. Schema
   inference leaves every quoted JSON value as `String`, but the deserializers
   (`JSONExtractTree` and the `deserializeText*` family) parse such a string
   into essentially any scalar destination, including `Decimal`, `Time` and
   `Time64`, which the previous enumerated list missed. So a row like
   `{"d": "1.23", "n": 1.5}` into `(d Decimal(9, 2), n UInt8)` still picked up
   the suffix even though `d` is valid and only `n` fails to parse. Replace the
   enumerated list with a principled predicate: a `String` inferred for any
   scalar destination is compatible; only numeric destinations (the reliable
   "text where a number is expected" signal) and nested/complex destinations
   (`Array`, `Tuple`, `Map`, which cannot be built from a single scalar string)
   are kept as a mismatch. This also stops the whitelist from missing further
   text-parseable scalar types in the future.

2. Named formats such as `JSONEachRow` default-fill omitted columns, so a row
   that leaves some columns out is not a structure mismatch. The old
   `inferred.size() == expected.size()` guard flagged such rows anyway, e.g.
   `{"a": 1.5}` into `(a UInt8, b String)` got the suffix merely because `b`
   was absent. Drop the size requirement for the name-based path and compare
   only the columns actually present in the input; keep the count check for
   positional formats (`TSV`, `CSV`, `Values`).

Also return early when schema inference produces no columns at all, so an
inference that yields nothing cannot be misread as a structure mismatch.

Adds `04606_insert_schema_mismatch_no_false_positive_json` covering both cases.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The Decimal case in `04606_insert_schema_mismatch_no_false_positive_json`
relies on schema inference leaving the quoted value `"1.23"` as `String`
(the premise of the review finding it covers). That holds by default, but
with `input_format_json_try_infer_numbers_from_strings` set to `1` inference
would read the quoted value as a number instead, changing the scenario. Pin
the setting to its default `0` so the test is robust against settings
randomization, mirroring the setting pin already used in
`04603_insert_schema_mismatch_diagnostic_stdin_tail`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Client/ClientBase.cpp Resolved
alexey-milovidov and others added 3 commits July 17, 2026 20:13
…atch diagnostic

Formats with named fields can legally carry fields unknown to the
destination table when `input_format_skip_unknown_fields` is enabled
(the default): the parser skips them. The diagnostic demoted such rows to
the positional comparison (an extra inferred column made the by-name
heuristic fail) and appended a misleading "structure mismatch" suffix to
an unrelated parse error, e.g. `{"a": 1.5, "extra": "x"}` inserted
into `(a UInt8)`. Decide by-name vs positional matching from the format
itself (`FormatFactory::checkIfFormatSupportsSubsetOfColumns`) and
ignore inferred columns unknown to the destination when the parser would
skip them; with the setting disabled the parser rejects the row precisely
because of the unknown field, so the mismatch keeps being reported there.
The client parses `INSERT ... FROM INFILE` through a `StorageFile`
pipeline, where the input format is created too deep to attach the lazy
parse-error diagnostic provider used by the inline/stdin paths, so a
schema mismatch in the file still produced only the bare parse error.
Classify the exception in the infile branch with `isParseError` and
compute the diagnostic from a bounded prefix of the file, decompressed
the same way the INSERT itself decompresses it and capped by
`input_format_max_bytes_to_read_for_schema_inference`. Glob paths
degrade gracefully (the diagnostic is skipped, best-effort).
…InsertDataSchemaMismatchDescriptionFromFile`

The `check_catch_all` style rule flags a `catch (...)` that silently swallows
exceptions unless the block has a comment containing the word `Ok`. The
best-effort catch added for the `INSERT ... FROM INFILE` diagnostic path in
`getInsertDataSchemaMismatchDescriptionFromFile` intentionally suppresses any
error (glob paths, unreadable files) so a diagnostic never raises a new error,
but its comment lacked the `Ok` marker, so `Style check` reported:

    src/Processors/Transforms/getSourceFromASTInsertQuery.cpp:246: catch (...) that silently swallows exceptions.

Reword the comment to state it is `Ok` to ignore the exception, matching the
existing catch block at line 79 in the same file. Comment-only change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… real parser per format

The comparison in `getInsertDataSchemaMismatchDescription` diverged from the actual
parser for two self-describing / `*WithNames*` cases, suppressing the explanation
exactly where the input structure really is the problem. Ask the format's own schema
reader how the parser identifies columns and validates types, and mirror it:

- Self-describing formats (the `*WithNamesAndTypes` family) carry the declared column
  types in the data, and `RowInputFormatWithNamesAndTypes::readPrefix` checks them
  against the destination exactly when `input_format_with_types_use_header` is set.
  The loose, supertype-based rule wrongly treated e.g. a declared `UInt64` as
  compatible with a `UInt8` column. Added `ISchemaReader::hasExactTypesFromData` (true
  for `FormatWithNamesAndTypesSchemaReader` with `with_types` and the setting on) and
  compare types exactly in that case.

- The old "every inferred name is a destination column" fallback flipped `*WithNames*`
  formats into name-based comparison even under `input_format_with_names_use_header = 0`,
  where the parser ignores the file's names and maps columns positionally. Decide the
  matching mode from `checkIfFormatSupportsSubsetOfColumns` (which is
  `with_names_use_header` for `*WithNames*`) OR the schema reader's
  `hasStrictOrderOfColumns` (false for `JSONEachRow` / `TSKV` / `BSONEachRow`), instead
  of the name-membership heuristic.

Both properties are read from a throwaway schema-reader probe, degrading to the
previous conservative behavior if it cannot be created.

Added `04609_insert_schema_mismatch_self_describing_and_positional.sh` covering both
cases and their no-false-positive controls.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rmats

The schema-mismatch diagnostic compared the schema returned by `readSchema`
against the destination, but for the metadata-based `JSON*` formats (`JSON`,
`JSONCompact`, `JSONColumnsWithMetadata`) that schema comes from the `meta`
section, which the parser treats differently depending on
`input_format_json_validate_types_from_metadata`:

- With validation enabled the parser checks the declared types against the
  destination exactly (`validateMetadataByHeader`), so the loose,
  supertype-based comparison wrongly treated e.g. a declared `UInt64` as
  compatible with a `UInt8` column and suppressed the explanation.
- With validation disabled the parser ignores the declared types entirely and
  reads the data by value (and positionally for `JSONCompact`), so the inferred
  `meta` schema does not describe what is parsed at all — comparing against it
  attached a bogus "structure mismatch" suffix to an unrelated value-level parse
  error, and for `JSONCompact` could hide a reordered-column mismatch.

Teach the schema readers to report this: add `ISchemaReader::schemaDescribesParsedData`
(false when the inferred schema is not what the parser reads/validates) and
extend `hasExactTypesFromData` to the metadata `JSON*` readers, both driven by
`input_format_json_validate_types_from_metadata`. `JSONRowSchemaReader` (used by
`JSON` and `JSONCompact`) also tracks whether the input actually carried a `meta`
section, so `JSON` inputs without metadata keep falling back to the loose
`JSONEachRow` inference. The diagnostic now probes the reader against the data,
suppresses the explanation when the schema does not describe the parse, and uses
an exact comparison when the declared types are validated exactly.

Add `04610_insert_schema_mismatch_metadata_json`.
…NSERT schema-mismatch diagnostic

The positional-column comparison in `getInsertDataSchemaMismatchDescription`
required the inferred column count to equal the destination count, which is
stricter than the real parser for formats that legally accept a variable number
of columns. `JSONCompactColumns` always default-fills omitted trailing columns
(see `JSONColumnsBlockInputFormatBase::read`), and `CSV` / `TSV` /
`CustomSeparated` / `JSONCompactEachRow` do the same (and skip extra columns)
when their `*_allow_variable_number_of_columns` setting is enabled. For such
inputs a genuine value-level parse error (e.g. `1.5` into a `UInt8` column) was
wrongly annotated with a "structure mismatch" explanation, just because schema
inference saw fewer columns than the destination has.

Mirror the parser instead: promote the existing `allowVariableNumberOfColumns`
capability from `IRowSchemaReader` to `ISchemaReader` (public), which already
reflects the setting for the row formats, and override it in
`JSONColumnsSchemaReaderBase` for the columnar JSON formats. When the format
allows a variable number of columns, the diagnostic no longer treats a differing
column count as a mismatch on the positional path and only compares the
overlapping positions, so a real per-column type mismatch is still surfaced.

Add `04611_insert_schema_mismatch_variable_number_of_columns` covering the
always-on case (`JSONCompactColumns`) and a setting-gated case (`TSV` with
`input_format_tsv_allow_variable_number_of_columns`), for both no-false-positive
and still-explained scenarios.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits November 9, 2026 22:35
…tch-diagnostic

Conflicts in `IInputFormat.h`, `ISchemaReader.h`, and `TemplateRowInputFormat.cpp`
were resolved by keeping master's `-WithMemoryTracking` container types and include
changes together with the PR's additions.

Master now lints `src/Processors/Formats` for plain standard containers, so the
PR's `getDeclaredTypeNames` now returns `UnorderedMapWithMemoryTracking`, and
`repeated_names` uses `UnorderedSetWithMemoryTracking`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…arse error

`getRowsReachedFromParseErrorMessage` trusted the rightmost row marker, but
`IRowInputFormat` appends the verbose diagnostic after its `(at row N)` marker,
and that diagnostic prints the successfully parsed fields of the failing row.
A fake marker in such a field (e.g. `hello (at row 50)\t1.5` in `TSV`) was then
chosen, schema inference sampled rows the parser never reached, and a bogus
structure mismatch was reported.

A lookalike cannot be told apart from the genuine marker by position, so take
the smallest bound over all occurrences of all marker forms. The genuine marker
is among them, so the bound never exceeds the true one. This also subsumes the
separate handling of lookalikes of the "(in file/uri ...)" suffix.

Add test `05616_insert_schema_mismatch_spoofed_row_marker_in_parsed_field`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 6 commits November 11, 2026 04:16
…tch-diagnostic

Resolve conflicts with the migration to `-WithMemoryTracking` containers in
`IInputFormat.h`, `ISchemaReader.h` and `TemplateRowInputFormat.cpp`, and
switch the containers added by this PR (`getDeclaredTypeNames`,
`declared_type_names`, `repeated_names`) to the tracking variants.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ple decoding

- The flat-text formats (`TSV`, `CSV`, ...) read a `Bool` with `SerializationBool`,
  which accepts the word forms (`yes`, `on`, `enabled`, ...) that schema inference
  keeps as `String`. Validate the sampled values with the `Bool` text deserializer
  there instead of treating every inferred `String` as a mismatch; the typed-token
  JSON formats, the formats that store typed values, and quoted numerics keep the
  stricter rule.
- The cast-on-read formats (`Native` under `input_format_native_allow_types_conversion`,
  `Parquet`, `Arrow`, ...) convert a `UInt128` column into `IPv6`
  (`convertFromUInt128toIPv6`), so an inferred `UInt128` is not a mismatch for an
  `IPv6` destination there.
- The sample replay used for value-level evidence now decodes only the column the
  evidence is needed for in the non-row formats that can read a subset of columns,
  so a large value in a column the failed insert never read is not decompressed
  only to explain the error. The decoded sample is also bounded in size; when the
  bound is exceeded the comparison stays inconclusive.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Processors/Formats/ISchemaReader.h
Address review: the decoded-bytes budget of the sample replay did not cover
the probe and inference reads of the schema reader. `NativeSchemaReader`
decodes every column of the first block, so a column the failed insert never
reached could declare a 1 GiB string in a few bytes of input, and the column
was resized to that size before the missing payload was detected.

Run the whole diagnostic under a child `MemoryTracker` of the query with a
hard limit proportional to the sample (`max(16 * sample size, 64 MiB)`): the
tracker rejects an allocation over the limit before it is made, and the
explanation is then omitted. Any exception of the diagnostic is now ignored,
so it can never replace the original error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ma_mismatch_native_inference_memory_budget`

The `query_log` entry of an HTTP query is written after the response is sent,
so poll for it with a bounded retry loop around `SYSTEM FLUSH LOGS`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=110626&sha=7bad5a2483d36d33033f5dd2f28fa54e69bab261&name_0=PR&name_1=Style%20check
#110626

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tch-diagnostic

Conflict resolution: master now creates the format of the async insert queue
lazily through `StreamingFormatExecutor::FormatCreator`, recreating it for
each entry when the format does not support `resetParser`. The
parse-error diagnostic provider is now installed in the format creator, so
every created format carries it, and the format context with the query
`SETTINGS` applied is kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 16, 2026 01:51
…tch-diagnostic

Conflicts with the `[[nodiscard]]` annotations from `modernize-use-nodiscard`
were resolved by keeping the schema reader capabilities added in this branch
(including `allowVariableNumberOfColumns` moved to `ISchemaReader`) and adding
`[[nodiscard]]` to them.
…ranch

Master enabled the `modernize-use-nodiscard` `clang-tidy` check and annotated
the existing const accessors of `ISchemaReader`, `IInputFormat` and the format
readers. Annotate the accessors this branch adds the same way, so `clang-tidy`
does not flag them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and resolved the conflicts with the [[nodiscard]] annotations from modernize-use-nodiscard; the const accessors this PR adds are annotated the same way now.

The only red check was Performance Comparison (amd_release, master_head, 3/8): bigint_formatting query 5 (toString(toUInt128(number))) was slower by about 70%. The PR doesn't touch number formatting or toString. Its previous head was based on master from 2026-11-14 03:18, and #117346 (clang-23) landed later that day, so the comparison binary was built with a different compiler. That is the likely cause, and the rerun on the merged head should show whether it goes away.

Comment thread src/Processors/Formats/IInputFormat.cpp Outdated
/// For a parse or conversion error, attach the schema-mismatch explanation if one is available.
if (parse_error_diagnostic_provider && isInsertDataErrorWorthExplaining(e.code()))
{
if (String diagnostic = parse_error_diagnostic_provider(getRowsReachedOnParseError()); !diagnostic.empty())

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.

[Major] Failures while preparing the optional diagnostic can replace the original parse exception. For streamed inserts, PrefixCapturingReadBuffer::getCapturedPrefix copies up to 1 MiB before entering the protected getInsertDataSchemaMismatchDescription implementation. If that copy exceeds the query memory limit, this unguarded callback invocation propagates MEMORY_LIMIT_EXCEEDED instead of the parse error being handled. The regular-file client provider likewise allocates, seeks, and reads before reaching that helper, and the helper's tracker allocation/setup also precedes its own try.

Please protect the complete diagnostic operation, including provider preparation and tracker setup, so a diagnostic failure preserves the original exception. Add a focused constrained-memory or injected-failure regression asserting that the original error code/message survives. This finding follows from the current exception paths; I have not executed the failure locally.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Fixed in 1cb1e57: IInputFormat::generate now guards the whole provider call (including the prefix copy in getCapturedPrefix and the regular-file read of the client provider), the diagnostic memory tracker is created inside the try of getInsertDataSchemaMismatchDescription, and the format/file checks of getInsertDataSchemaMismatchDescriptionFromFile moved into its try. Added the insert_schema_mismatch_diagnostic_fail failpoint and 05832_insert_schema_mismatch_diagnostic_failure_keeps_original_error (run in a separate clickhouse-local process), which asserts the original CANNOT_PARSE_* error survives and no MEMORY_LIMIT_EXCEEDED leaks.

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.

[Major] The error-preservation gap remains after 1cb1e57ff7d7 at src/Processors/Formats/IInputFormat.cpp:80-81: e.addMessage(diagnostic) is outside the new protected region. A provider can return a nonempty explanation successfully, then attachment can still throw. Exception::addMessage copies the explanation into MessageMasked (Exception.h:245, Exception.cpp:135-140) and appends it to the original message through Poco::Exception::extendedMessage; neither allocation is protected against a memory exception here. That exception escapes this handler instead of rethrowing the original parse error.

Please include attachment in the same best-effort guard. The new regression injects failure before calling the provider, so it cannot cover this remaining path; inject a failure after a nonempty explanation has been produced, at attachment, and assert that the original error survives. This is a source trace; I have not executed the allocation-failure case locally.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Fixed in c696e6e: e.addMessage(diagnostic) is now inside the same best-effort guard in IInputFormat::generate. Added the insert_schema_mismatch_diagnostic_attach_fail failpoint, which throws after the provider has returned a nonempty explanation and right before it is attached, and extended 05832_insert_schema_mismatch_diagnostic_error_keeps_original_error with that case: the original CANNOT_PARSE_* error survives and the explanation is omitted.

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.

[Major] c696e6e135fa protects attachment in IInputFormat::generate, but the same error-preservation gap remains in the separate FROM INFILE caller at src/Client/ClientBase.cpp:2945. After the file helper returns, e.addMessage(description) still runs outside a protective guard. Copying, masking, or appending that explanation can throw, for example std::bad_alloc under process memory pressure, and replace the original parse exception. The helper's internal guard ends before this call.

Please protect preparation and attachment consistently across both callers, preferably through a shared helper, and exercise attachment failure through INSERT ... FROM INFILE. The attachment failpoint in 05832 currently covers only IInputFormat. This remaining path is established by source tracing; I have not executed an allocation-failure reproduction here.

alexey-milovidov and others added 6 commits November 19, 2026 04:24
…diagnostic keeps the original error

The explanation is an optional addition to a parse error, but parts of preparing it ran
outside the protected `getInsertDataSchemaMismatchDescription` implementation: a provider
copying the captured prefix (`PrefixCapturingReadBuffer::getCapturedPrefix`), the
regular-file provider of the client reading the file, and the setup of the diagnostic memory
tracker. An exception there, e.g. `MEMORY_LIMIT_EXCEEDED`, replaced the original parse error.

Guard the whole provider call in `IInputFormat::generate`, create the tracker inside the
`try` of `getInsertDataSchemaMismatchDescription`, and move the format and file checks of
`getInsertDataSchemaMismatchDescriptionFromFile` into its `try`. Add the
`insert_schema_mismatch_diagnostic_fail` failpoint and a test that the original error
survives it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…detection disagrees with the parser

`FormatWithNamesAndTypesSchemaReader::tryDetectHeader` and
`RowInputFormatWithNamesAndTypes::tryDetectHeader` decide by different rules whether the first
row of a plain `CSV` / `TSV` / `CustomSeparated` holds column names: the reader looks at the
types of the following rows, the parser at whether the first row and the destination names are
a subset of one another. With the destination `(s String, n UInt8)` and the rows `n,"1"` and
`bar,1.5`, the reader took the first row for names while the parser read it as data and failed
only on `1.5`, so the diagnostic blamed a structure mismatch for a value-level error.

The schema reader now remembers the raw fields of the rows it looked at, and the new
`headerDetectionAgreesWithParser` capability reproduces the parser's decision for the
destination names (reading the fields like `readRowForHeaderDetection` does). When the
decisions differ, the explanation is omitted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ort_nested_json`

The test relied on `Form` schema inference appending each field to the previous ones, which
made `x=1.5` inferred as a string. #132172 fixed
that on master, so `1.5` is now inferred as a number and is a value-level error, not a structure
mismatch. Use `x=abc`, which is inferred as a string, to keep testing the intent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tch-diagnostic

Conflict in `ParallelParsingInputFormat.cpp`: master removed `first_parser_finished`
(the reading thread now parses the first unit itself); keep recording
`header_rows_in_first_unit` there, which still happens before any other parser is scheduled.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…stic

- Mark `readNamesFromFields` and `readHeaderDetectionValuesFromFields` as `[[nodiscard]]` (`modernize-use-nodiscard`).
- Say that the swallowed exception is Ok in the `catch (...)` around `headerDetectionAgreesWithParser`.
- Rename `05832_insert_schema_mismatch_diagnostic_failure_keeps_original_error`: test names must not contain 'fail'.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and resolved the conflict in ParallelParsingInputFormat.cpp: master removed first_parser_finished because the reading thread now parses the first unit itself. header_rows_in_first_unit is still recorded in the same place, which is still before any other parser is scheduled.

Fixed the red checks of the previous head:

  • Build (arm_tidy): readNamesFromFields and readHeaderDetectionValuesFromFields are now [[nodiscard]].
  • Style check: the catch (...) around headerDetectionAgreesWithParser now says the swallowed exception is Ok, and 05832_insert_schema_mismatch_diagnostic_failure_keeps_original_error is renamed to 05832_insert_schema_mismatch_diagnostic_error_keeps_original_error (test names must not contain fail).

Locally, on the merged tree, all 97 insert_schema_mismatch tests pass.

alexey-milovidov and others added 3 commits November 24, 2026 18:11
… the explanation fails

`e.addMessage(diagnostic)` in `IInputFormat::generate` was outside the best-effort guard, although it
allocates too, so a failure there could replace the original parse error. It is inside the guard now.
The new `insert_schema_mismatch_diagnostic_attach_fail` failpoint injects a failure after a nonempty
explanation has been produced, and `05832_insert_schema_mismatch_diagnostic_error_keeps_original_error`
checks that the original error survives.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…on_map_as_array_of_tuples`

Schema inference types `[]` as `Array(Nothing)` and substitutes `String` for the incomplete element
type, so the pair-type guard reported a structure mismatch for a valid empty `Map` when a sibling
column failed to parse. A `String` element is now treated as a placeholder as long as every sampled
array at that path is empty; a non-empty array that is not an array of pairs is still explained.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (no conflicts) and addressed the two open review threads (c696e6e, 2080fe4).

The only red check of the previous head was Stress test (amd_debug): the hung check found a cancelled SELECT ... FROM icebergLocalCluster(...) SETTINGS cluster_function_wait_for_replica_ms = 9223372036854775 query (from 05620_cluster_function_wait_for_replica_ms_overflow) that did not stop. This is unrelated to the PR and is fixed by #133412, which was merged on 2026-11-21 after the previous merge base; the fix is in the branch now.

Comment on lines +1651 to +1653
return is_valid_text(destination, destination_serialization, text)
|| (!format_reads_string_values_as_whole_text
&& is_valid_text(number_type, number_serialization, text));

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.

[Major] Preserve empty-field defaults when validating sampled CSV values

With destination (a UInt8, n UInt8), input_format_csv_detect_header=0, input_format_csv_missing_nullable_as_empty_string=1, and the default input_format_csv_empty_as_default=1, the input ,1.5\n fails only on the fractional n: CSVFormatReader::readField default-fills the empty a. Changing the last value to 1 makes the complete insert valid and yields (0, 1).

Both inference passes replace the empty field's incomplete type with Nullable(String). Replaying under that inferred header changes its meaning: missing_nullable_as_empty_string makes the sample hold "" instead of NULL. The placeholder predicate does not recognize this defaulted field, and both whole-text numeric checks here reject "", so the diagnostic falsely blames a structural mismatch on the valid a. The same loss of evidence occurs with schema_inference_make_columns_nullable=0, where replay defaults the inferred plain String to "".

Please preserve empty/default provenance when replaying with inferred types, or keep these comparisons inconclusive according to the actual format/destination default rules. Add the failing-sibling case and its successful control. This is established by tracing the current inference, replay, and CSVFormatReader::readField paths; it has not been executed locally.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unexpected FORMAT Parsing Error from INSERT INTO FUNCTION url()

2 participants