Skip to content

Add input_format_skip_duplicated_fields to keep the first value of a field repeated in a row - #133483

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:input-format-skip-duplicated-fields
Nov 23, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:input-format-skip-duplicated-fields

Conversation

@groeneai

@groeneai groeneai commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #133468

Changelog category (leave one):

  • New Feature

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

Added the input_format_skip_duplicated_fields setting (disabled by default). When it is enabled, a field that appears more than once in a row of JSONEachRow (and the other formats that read JSON objects the same way, including nested fields read with input_format_import_nested_json), BSONEachRow, TSKV or Form keeps its first value instead of throwing the Duplicate field found exception, and schema inference takes the type of such a field from its first value. Closes #133468.

Description

A row with the same key twice was rejected by JSONEachRow, BSONEachRow, TSKV and Form (Duplicate field found) and by their schema inference (Duplicate column name found while schema inference), with no setting to accept it. For JSONEachRow the result also depended on the key order: with input_format_json_ignore_unnecessary_fields = 1, a duplicate after all columns were read was skipped without a lookup.

With the new setting each of the four readers skips the value of a field already read in the current row with the skip function it uses for unknown fields, so the first value is kept, as with type_json_skip_duplicated_paths. Each of the five schema readers skips a repeated field the same way before inferring its type, including a JSONObjectEachRow field that repeats the format_json_object_each_row_column_for_object_name column. With input_format_column_name_matching_mode = 'ignore_case' the JSONEachRow and BSONEachRow schema readers, like their row readers, treat names that differ only in case as one field. With input_format_skip_unknown_fields = 0 and the setting enabled, JSONEachRow looks up the keys that follow a complete row, so a trailing duplicate is skipped and an unknown field is still an error. The setting and the matching mode join the schema cache key of row-based formats. With the setting disabled the behaviour is unchanged, and the errors above name the setting as a workaround.

Not covered: duplicate names in *WithNames headers, JSONColumns, and keys inside a named Tuple value.

Validation: 05843_input_format_skip_duplicated_fields covers the cases of the issue, nested fields, JSONObjectEachRow, the three other formats, repeated values that inference cannot type (a BSON Regexp, a value deeper than max_parser_depth) and an INSERT; 05844_input_format_skip_duplicated_fields_schema_cache checks that a schema inferred with the setting is not reused without it or with another matching mode. Reverting any single hunk fails one of them, and 50 randomized runs pass.


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

Version info

  • Merged into: 26.12.1.298-master (included in 26.12 and later)

…repeated field

A row with the same key twice was rejected by JSONEachRow (and the formats
reading JSON objects the same way), BSONEachRow, TSKV and Form with
"Duplicate field found", and by their schema inference with "Duplicate column
name found while schema inference", with no way to accept it.

The new setting (default false) makes each reader skip the value of a field
already read in the current row with the skip primitive it uses for unknown
fields (skipJSONField, skipBSONField, the NullOutput sink, Form's own value
read), so the first value is kept, consistent with
type_json_skip_duplicated_paths. Schema inference ignores a repeated name in
IRowWithNamesSchemaReader::readSchema, the base of all five schema readers, so
the type comes from the first value.

The JSONEachRow fast path for input_format_json_ignore_unnecessary_fields
skips keys after a complete row without a lookup and reports them as unknown
when input_format_skip_unknown_fields = 0; with the new setting enabled and
unknown fields not skipped, those keys take the normal lookup, so a trailing
duplicate is skipped and an unknown field is still an error. TSKV keeps the
column index at -1 for a skipped duplicate so its garbage-after-field cleanup
cannot pop the kept value.

The setting changes what schema inference returns, so it joins the schema
cache key shared by row-based formats (like max_parser_depth); four tests that
print the whole key gain the field.

Closes ClickHouse#133468

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 4 findings; 1 full pass, no fix round needed).

# Sev Finding Verdict Evidence / action
1 ❌ A discarded duplicate's inferred type leaves a raw pointer in JSONInferenceInfo; a reused address can mark an unrelated column as negative (ISchemaReader.cpp readSchema) DISAGREE Pre-existing on master without this setting: DESC format(JSONEachRow, '{"x":0}\n{"x":-1}\n{"y":1}\n{"y":18446744073709551615}') fails with TYPE_MISMATCH on 26.12.1.1, because chooseResultColumnType drops an equal later-row type whose pointer stays registered. The cause is the pointer bookkeeping in SchemaInferenceUtils, so it needs its own fix there.
2 ❌ A duplicate BSON string with an invalid size is skipped without validation (BSONEachRowRowInputFormat.cpp readRow) DISAGREE The duplicate skip reuses skipBSONField, which the reader already applies to every unknown field under the default input_format_skip_unknown_fields = 1: master accepts the same malformed value under an unknown key. The kept value and the document size are still validated.
3 ⚠️ No test for the default trailing-duplicate behavior DISAGREE Already pinned by 04027_json_input_format.sql (a trailing duplicate accepted through the same fast path, rows 444).
4 ⚠️ The cache test passes if nothing is cached DISAGREE With the cache-key field reverted, 05844 prints the cached type twice and no error, so the entry is stored and reused in this test. The four references that print the whole key also pin the field.

Also checked, not changed: keys inside a named Tuple value (JSON object contains duplicate key) are a type serialization outside this setting, as stated in the description.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261122-043800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT * FROM format(JSONEachRow, 'name String, url String', '{"url":"a","url":"b","name":"x"}') gives Code: 117 Duplicate field found while parsing JSONEachRow format: url on master; with input_format_skip_duplicated_fields = 1 master gives UNKNOWN_SETTING, this PR gives x a.
b Root cause explained? Each row-by-name reader (JSONEachRow family, TSKV, BSONEachRow, Form) throws unconditionally when its per-row seen_columns bitmap meets a column twice, and IRowWithNamesSchemaReader::readSchema throws on a repeated name. The key-order dependence comes from the input_format_json_ignore_unnecessary_fields fast path, which skips keys after a complete row without a lookup.
c Fix matches root cause? Yes. The new setting is checked inside the existing duplicate branches; the skip reuses each reader's own skip primitive (skipJSONField, skipBSONField, the NullOutput sink, Form's own value read). No new mechanism.
d Test intent preserved / new tests added? New 05843_input_format_skip_duplicated_fields.sql (cases of the issue, nested fields, JSONObjectEachRow, TSKV/BSONEachRow/Form with a structure and with inference, INSERT) and 05844_input_format_skip_duplicated_fields_schema_cache.sh. No existing test logic changed; four references that print the whole schema cache key gain one field.
e Both directions demonstrated? Yes. Both new tests fail on the same commit without the src/ change and pass with it. Reverting each hunk alone fails at least one assertion (mutation table recorded for all 9 hunks).
f Fix is general across code paths? Yes: all four readers (incl. JSONStringsEachRow, JSONObjectEachRow, JSON data rows, import_nested_json), the one shared schema reader, and the shared schema cache key. Parallel parsing reuses the same readers.
g Fix generalizes across inputs (params/datatypes/wrappers)? The skip is type-independent (raw value skip). Probed: Nullable, LowCardinality, Array, Map, object/array duplicate values in JSON and BSON, null first value, triple duplicates, escaped TSKV and url-encoded Form values, parallel parsing on and off, defaults_for_omitted_fields.
h Backward compatible? (maintainer-approved exception only) Yes. Default 0 with a 26.12 history entry; with the setting off the error messages are byte-identical and a 273-test format/schema-inference set has no new failure. The in-memory schema cache key gains one field.
i Invariants and contracts preserved? On the skip path seen_columns, read_columns and the column are untouched, so each column gets exactly one value per row and defaults bookkeeping follows the first occurrence. TSKV keeps index = -1 for a duplicate, so its "garbage after field" cleanup cannot remove the kept value. Form consumes the value before returning. Schema inference skips before any assignment, so the first type and hint win.

Session id: cron:clickhouse-impl-slot-6:20261122-032100

@clickhouse-gh

clickhouse-gh Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c8db5cd]

Summary: ✅


AI Review

Summary

Adds opt-in input_format_skip_duplicated_fields support to the documented row formats, preserving the first value during parsing and schema inference and separating schema cache entries by the relevant settings. All prior inline findings are fixed, and no new actionable findings remain. Both new stateless regression tests passed locally using the Fast test binary for c8db5cd9981131a9320ab261af8b4810c9ed4f77.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-feature Pull request with new product feature can be tested Allows running workflows for external contributors comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). labels Nov 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c8db5cd99 with master 91b044d19 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

811 translation units recompiled, 4668 s compile time in total, 811 of them have a recent master baseline.

Job report

groeneai and others added 2 commits November 22, 2026 07:28
With input_format_skip_duplicated_fields, every schema reader still inferred
the value of a repeated field, and only IRowWithNamesSchemaReader::readSchema
dropped its name afterwards. So a value the row reader skips could fail
inference: a BSON Regexp (no inferable type), or a JSONEachRow, TSKV or Form
value nested deeper than max_parser_depth. Each schema reader now skips a
repeated top-level field before inferring it, with the skip it uses when
reading (skipJSONField, skipBSONField, the value already read for TSKV and
Form), so readSchema no longer sees repeated names with the setting enabled.

A JSONObjectEachRow field repeating the column set by
format_json_object_each_row_column_for_object_name is skipped by the row
reader, which fills that column first, but inference returned both names and
failed with "column with this name already exists". readSchema now drops such
a field and keeps the static String column.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With input_format_skip_duplicated_fields, the JSONObjectEachRow row reader
fills the format_json_object_each_row_column_for_object_name column first, so a
field of the same name inside the object is a repeated one and is skipped. Schema
inference still inferred its value and dropped the name only afterwards, so the
discarded value could fail inference: a type conflict between rows
(`{"r1":{"id":[1]},"r2":{"id":1}}`) or a value nested deeper than
max_parser_depth.

The JSON row inference helper now takes the name already read for the row and
skips such a field with skipJSONField, returning it with a null type. Returning
the name keeps a row made only of that field from looking empty, so
`{"user1":{"id":"user1"}}` still infers `id String` instead of failing with
EMPTY_DATA_PASSED; readSchema still drops the name and keeps the String column.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 22, 2026
@alexey-milovidov alexey-milovidov self-assigned this Nov 22, 2026
…rors

The "Duplicate field found while parsing <format> format" errors of
JSONEachRow, TSKV, BSONEachRow and Form, and the "Duplicate column name
found while schema inference" errors of the schema reader these formats
share, now name the setting as the workaround, the same way the JSON type
errors name type_json_skip_duplicated_paths.

The header errors of the *WithNames formats and the Freeform schema
inference error keep their text: the setting does not apply to them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Formats/JSONUtils.cpp Resolved
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 22, 2026 15:53

AI review of a later commit does not approve the PR, see the AI Review comment.

…e_case

With `input_format_column_name_matching_mode = 'ignore_case'` the JSONEachRow
and BSONEachRow row readers resolve `a` and `A` to the same column, so with
`input_format_skip_duplicated_fields` the second one is a repeated field.
Schema inference compared the raw names and kept both, and the reader then
rejected the inferred schema with `Ambiguous field`. Inference now compares
the lowercased names under `ignore_case`, in the JSON and BSON schema readers
and for the JSONObjectEachRow object-name column. With `auto` and `match_case`
both spellings stay columns, since the reader then matches each one exactly.
TSKV and Form readers never fold names, so their inference is unchanged.
The schema cache key now includes the matching mode.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 23, 2026
Merged via the queue into ClickHouse:master with commit e516aec Nov 23, 2026
195 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A setting to skip duplicate fields in JSONEachRow instead of throwing Duplicate field found

3 participants