Skip to content

Create a new input format for each streamed input unless the format resets all its state - #129209

Merged
Algunenano merged 8 commits into
ClickHouse:masterfrom
groeneai:reuse-input-format-only-if-it-resets
Nov 13, 2026
Merged

Algunenano merged 8 commits into
ClickHouse:masterfrom
groeneai:reuse-input-format-only-if-it-resets

Conversation

@groeneai

@groeneai groeneai commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed lost, rejected or misparsed rows when several INSERT ... FORMAT SQLite, One, Npy, MySQLDump, JSON, RowBinaryWithNamesAndTypes, CustomSeparated, Template, TSV or Values queries are combined into one asynchronous insert batch (asynchronous inserts are enabled by default), and in FileLog tables with these formats: each input is now parsed as if it were the only one.

Description

Closes: #122351
Related: #129140 (replaced by this PR)
Related: #129109 (replaced by this PR)
Related: #128943 (the same class in MsgPack)

On 26.10.2.103, one asynchronous insert batch of two FORMAT SQLite inputs inserts only the first one's rows and three FORMAT One inputs insert one row. The other formats in the changelog entry fail the same way.

StreamingFormatExecutor (async inserts, Kafka, NATS, RabbitMQ, FileLog) reuses one format for all inputs and trusts resetParser to restore a fresh state; 33 of the 82 input format names did not.

A format is now reused only if its registration passes supports_reset_parser = true (FormatFactory::registerInputFormat); any other is created anew per input, so a new format cannot break streamed inputs. 76 names pass it: those whose reset is complete, plus seven reset completions (TSV CRLF check, CustomSeparated header width, detected header and CSV delimiter, RowBinaryWithNamesAndTypes types, Template CSV delimiter and row number, Values parser mode). Reuse is kept because some formats are costly to build (CapnProto parses a schema, Regexp compiles one). One, Npy, MySQLDump, SQLite, JSON and DWARF are re-created, with no per-format code.

Validation: 02187_async_inserts_all_formats now also inserts each format as a batch of two inputs, plus targeted cases. 13 cases fail on master and 26.10.2.103, 50/50 runs pass with the fix, and undoing a reset completion (except the Template row number, seen only in error text) or passing it for SQLite or One reddens exactly its case. Reused formats still rely on resetParser; the batch case checks those it inserts. Price (debug build): FileLog with 200k JSONEachRow/TSV records is unchanged; re-creating costs about 3 us per input (one flush of 4500 JSON entries: 37-43 ms, now 51-76 ms); the Values reset about 10 us per input with an expression (4500 (1 + 1) entries: 48-49 ms, now 91-97 ms; literals unchanged).


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

Version info

  • Merged into: 26.11.1.2238-master (included in 26.11 and later)

groeneai and others added 5 commits November 4, 2026 05:19
…self

StreamingFormatExecutor (async insert flushes, Kafka, Kafka2, NATS,
RabbitMQ, FileLog) kept one input format object for many independent
inputs and called resetParser() between them, trusting every format to
bring itself back to the state of a fresh object. Nothing enforced that:
32 of the 82 input format names kept some per-input field (One `done`,
Npy `read_rows`, MySQLDump `table_name` and column mapping, SQLite
flags and database, JSON `parse_as_json_each_row`, DWARF section
extractors, TSV `first_row`, CustomSeparated `columns` and the detected
header, RowBinaryWithNamesAndTypes `read_data_types`, Template
`row_num`), so a later input of an async insert batch or a later
message lost rows, was rejected, or was parsed with the previous
input's state. Per-format resetParser fixes (ClickHouse#128943, ClickHouse#129109, ClickHouse#129140)
leave the default unsafe for the next format and the next field.

Invert the default: a format is reused only when its name is registered
with FormatFactory::markInputFormatSupportsResetParser; any other format
is released after each input and created anew for the next one. The
executor now takes a format creator and an AddingDefaultsTransform
creator (the transform holds a reference to the format). The streaming
engines compute their single-threaded parser resources once and share
them between created formats.

Marked: the 50 names whose reset is complete and 26 hot names completed
here with one statement each (TSV first_row, CustomSeparated columns,
WithNamesAndTypes is_header_detected, RowBinary read_data_types,
Template row_num). Reuse matters for them: a fresh CapnProto, Template,
Protobuf, Regexp or AvroConfluent object reads or compiles schemas.
Not marked, so re-created with no per-format code: One, Npy, MySQLDump,
SQLite, JSON, DWARF. DWARF's incomplete resetParser is deleted.

02187_async_inserts_all_formats now also inserts every format as one
batch of two different inputs, plus targeted cases for the leaks that
a same-shaped pair does not show, and a FileLog case.

Closes ClickHouse#122351

Co-Authored-By: Claude Opus 5.5 <[email protected]>
TemplateRowInputFormat rewrites settings.csv.delimiter and
csv.custom_delimiter before every CSV-escaped column, so an input ends
with the values for the last CSV column of the row format. The format is
marked as resetting all per-input state, but resetParser did not restore
them, and the next input's result-set prefix skipped its ${:CSV} field
with the previous input's delimiter: in one async insert batch the second
input was rejected with "expected ','". Restore both to the values of a
fresh object, and add a Template batch case to
02187_async_inserts_all_formats.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`Values` is reused across streamed inputs, but its `resetParser` kept each
column's parser mode, templates and template deduction counters unless the
previous input threw. Only the streaming mode understands `DEFAULT`, so after
an input whose column needed an expression (`(1 + 1)`), a later `(DEFAULT)`
in the same async insert batch went through the template/expression path and
was rejected with `Unknown expression identifier DEFAULT`, while a fresh
format inserts the column default. Reset every per-column field to its
constructor value; `templates_cache` is kept, since it is keyed by the
expression structure and a fresh object would rebuild the same entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `format_custom_escaping_rule = 'CSV'`, `CustomSeparatedFormatReader::updateFormatSettings`
rewrites `csv.delimiter` of the reader's own settings copy before each field, but only when the
next delimiter is one character; a multi-character delimiter goes to `csv.custom_delimiter` and
leaves `csv.delimiter` as it was. So the last column of one input (row delimiter `'\n'`) left
`csv.delimiter = '\n'`, and a reused reader parsed column 0 of the next input with it: a `Bool`
followed by the `', '` field delimiter was rejected, while a fresh reader accepts it. The reader
now restores the constructor's delimiter and clears the custom one in `setReadBuffer`, which
runs for every new input. `02187_async_inserts_all_formats` gains the batch case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop two comments on the StreamingFormatExecutor creator aliases that restate their names.

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

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (rounds 1-4): 3 fixed, 2 dismissed with evidence
Finding Verdict
❌ Template is marked as resetting itself, but the CSV delimiter rewritten per column was not restored, so a ${:CSV} prefix field of the next input was read with the previous input's delimiter Agreed, fixed: restored in TemplateRowInputFormat::resetParser, with a batch case in 02187
❌ Values is marked as resetting itself, but kept the per-column parser mode, so (DEFAULT) after an input that needed an expression in that column was rejected Agreed, fixed: modes and deduction counters reset in ValuesBlockInputFormat::resetParser (template cache kept), with a batch case in 02187
❌ CustomSeparated with CSV escaping and a multi-character field delimiter kept the previous input's csv.delimiter, so a Bool in the first column of the next input was rejected Agreed, fixed: restored per input in CustomSeparatedFormatReader::setReadBuffer, with a batch case in 02187
⚠️ The test cannot observe whether a marked format is reused Dismissed: reuse has no data-visible effect; it is shown by the removed-reset mutations (each reddens only because the format is reused) and by the FileLog timing
⚠️ No test batches two Vortex inputs Dismissed: Vortex was already reused for every input before this PR and its resetParser is unchanged; the mark keeps that behaviour
💡 Parquet reported_count and RawBLOB done_count_rows are not reset Not changed: read only in count-only mode, which no streamed input uses
💡 With input_format_record_errors_file_path, a re-created format writes its own errors file per input Not changed: this is what separate inserts do

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 02187_async_inserts_all_formats (extended) fails the same 13 cases on every run on master and on official 26.10.2.103.
b Root cause explained? StreamingFormatExecutor reuses one format object for all inputs and trusts resetParser; 33 of 82 input format names did not reset all per-input state, so later inputs lose rows, are rejected or are misparsed.
c Fix matches root cause? Yes. The executor reuses only formats registered as resetting completely and creates every other format anew per input; forgetting the mark is safe.
d Test intent preserved / new tests added? The existing single-insert checks are unchanged; the test adds a two-input batch for every round-trippable format and 12 targeted cases (One, Npy, MySQLDump, JSON, CustomSeparated x3, RowBinaryWithNamesAndTypes, TSV, Template, Values, FileLog).
e Both directions demonstrated? Master: FAIL (13 cases). Fix: OK, 50/50 randomized. Each of 9 mutation binaries (SQLite or One marked, one reset removed) reddens exactly its own case.
f Fix is general across code paths? All 6 executor callers (async insert, Kafka, Kafka2, NATS, RabbitMQ, FileLog) and all 82 names; reset/release on every exit path incl. cancellation. Kafka integration tests pass (109/109; test_kafka_formats 2/2 re-run on the final binary).
g Fix generalizes across inputs (params/datatypes/wrappers)? Every round-trippable format in the batch loop; heterogeneous inputs (header widths, unknown-column types, row counts, detected header, CRLF, a Template row whose last CSV column ends with another delimiter, a CustomSeparated CSV input with a multi-character field delimiter, a Values expression then DEFAULT); AggregateFunctionStatesFromValues wrapper forwards the flag.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; marked formats run the same code; unmarked formats parse each input like a single insert.
i Invariants and contracts preserved? Input k is parsed as by a fresh format; no member outlives its format; resetReadBuffer still runs before destruction; creation errors propagate instead of reaching on_error.

Session id: cron:clickhouse-impl-slot-40:20261104-081600

@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a820384]

Summary: ✅


AI Review

Summary

Reviewed #129209 at a820384ac8e639a02df03db106d6a9987e978ed5, including all prior discussion. The change makes input-parser reuse opt-in, recreates parser-dependent default transforms, and completes per-input resets to prevent lost or misparsed rows. No actionable findings.

Missing context / blind spots
  • ⚠️ No local build was available, so runtime tests were not rerun. 02187_async_inserts_all_formats passed full stateless CI on 013785db; its test, executor, and async-insert implementation are unchanged at the current head. Current-head Fast test skips this test via no-fasttest; a current-head full stateless run would complete runtime validation after the master merge.
Final Verdict

Status: ✅ Approve. No new inline findings to post.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 4, 2026
@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @CheSema, could you review this and add the can be tested label so CI runs? StreamingFormatExecutor (async inserts, Kafka, NATS, RabbitMQ, FileLog) reused one input format for every input and relied on resetParser, which 33 of the 82 input format names did not implement completely; it now reuses only formats registered with FormatFactory::markInputFormatSupportsResetParser and creates any other format anew per input.

@clickhouse-gh clickhouse-gh Bot added comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). can be tested Allows running workflows for external contributors labels Nov 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a820384ac with master c89eff230 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.58, programs/clickhouse-keeper ×0.61 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.8 s 10.7 s +7.4 s (+220%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.1 s +5.2 s (+260%)
Compile time of recompiled translation units

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

Job report

@Algunenano Algunenano self-assigned this Nov 4, 2026

@Algunenano Algunenano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai I like the general direction of this PR, but this should be part of the format registration, not require and extra call via markInputFormatSupportsResetParser. markFormatSupportsSubsetOfColumns is not a good example and we should probably remove it.

Also please update vs master

groeneai and others added 2 commits November 11, 2026 16:36
…only-if-it-resets

# Conflicts:
#	src/Processors/Formats/IInputFormat.h
Replace the separate `FormatFactory::markInputFormatSupportsResetParser`
call with a `supports_reset_parser` argument of `registerInputFormat` and
`registerRandomAccessInputFormat`, so the property is stated where the
format is registered. It defaults to false: a format that does not pass it
is created anew for each streamed input. The same 76 names pass true.

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

Copy link
Copy Markdown
Collaborator Author

Thanks, both done:

  1. The property is now part of the registration: registerInputFormat and registerRandomAccessInputFormat take supports_reset_parser (default false, so a format that does not pass it is created anew for each streamed input), and markInputFormatSupportsResetParser is removed. The same 76 names pass true. 013785d
  2. Merged master; the only conflict was the owned_buffers container type in IInputFormat.h. b30f725

On the new head 02187_async_inserts_all_formats passes, and its 13 cases still fail on today's master. Passing true for One reddens exactly its two cases, so the argument reaches StreamingFormatExecutor. I did not touch markFormatSupportsSubsetOfColumns in this PR.

@Algunenano Algunenano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think this is quite verbose, but it's the right defaults

Blargian pushed a commit to deeox/ClickHouse that referenced this pull request Nov 12, 2026
…allel replicas

With parallel replicas, an `INSERT ... SELECT` into a `Join` table runs on every replica, and the inserts share the
initial query id. `StorageJoin` takes its write lock by that id, so when two replicas insert at the same time, the second
one fails with `DEADLOCK_AVOIDED`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=129209&sha=013785db07d54a273f8795ffd2b6a00f4cb1345f&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29
Related: ClickHouse#129209
Related: ClickHouse#129328

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 013785d

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05494_join_hashed_keys flaky, not from this PR: with parallel replicas the test's INSERT ... SELECT into a Join table runs on more than one replica under the same initial query id, so the second insert fails with DEADLOCK_AVOIDED (StorageJoin: cannot insert data because current query tries to read from this storage). 17 reruns with the same settings passed #130995 (external, merged)
Performance Comparison (arm_release, master_head, 1/6 to 6/6) infra, not from this PR: performance test selection got GitHub API 403 Client Error: rate limit exceeded while reading the changed files, so no performance query ran on any shard #131070 (external, merged)
Mergeable Check, PR praktika rollups of the rows above #130995 and #131070 (external, merged)

Both fixes were merged after this head's CI started. The 5 NOT_FAILED rows of the stateless job are tests that passed while listed in parallel_replicas_blacklist.txt; they are not failures.

Session id: cron:our-pr-ci-monitor:20261112-200351

@Algunenano
Algunenano enabled auto-merge November 13, 2026 14:25
@Algunenano
Algunenano added this pull request to the merge queue Nov 13, 2026
Merged via the queue into ClickHouse:master with commit b2b1297 Nov 13, 2026
204 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 13, 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-bugfix Pull request with bugfix, not backported by default 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.

Batched async RowBinaryWithNamesAndTypes inserts skip columns with stale types

3 participants