Skip to content

Reset the MsgPack parser between streamed inputs - #128943

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:reset-msgpack-parser-between-inputs
Nov 3, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:reset-msgpack-parser-between-inputs

Conversation

@groeneai

@groeneai groeneai commented Nov 3, 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 a server abort, wrong rows, or a rejected valid row when a MsgPack input that ends in the middle of an object is followed by another input parsed by the same format, as with the entries of one asynchronous insert batch or the messages of a streaming engine such as Kafka with kafka_handle_error_mode = 'stream'.

Description

No related open issue found. On the official 26.10.2.103 image, two asynchronous MsgPack inserts into CREATE TABLE ai (id UInt64, arr Array(UInt8)) ENGINE = MergeTree ORDER BY id, a truncated one followed by a valid one, abort the server at the batch flush:

URL='http://localhost:8123/?async_insert=1&wait_for_async_insert=0&async_insert_busy_timeout_min_ms=3000&async_insert_busy_timeout_max_ms=3000'
printf '\x07\x93\x01' | curl -s "$URL&query=INSERT%20INTO%20ai%20FORMAT%20MsgPack" --data-binary @-          # array of 3, 1 present
printf '\x01\x93\x01\x02\x03' | curl -s "$URL&query=INSERT%20INTO%20ai%20FORMAT%20MsgPack" --data-binary @-  # valid

Release builds die with libc++ Hardening assertion this->has_value() failed: optional operator* called on a disengaged value, debug builds with Logical error: 'info_stack.top().array_size.has_value()'. A truncated uint32 (\xce\x00) followed by the rows 1, 2, 3, 4 inserts the one wrong row 16909060 instead.

StreamingFormatExecutor reuses one input format for all entries of a batch (and for Kafka, RabbitMQ, NATS and FileLog messages) and calls resetParser between them, also after a parse error. MsgPackRowInputFormat::resetParser reset only the visitor, not the msgpack-c parser, which keeps its open containers and its partly read value when an object is cut short. The next input was parsed as the continuation of the broken one.

resetParser now calls parser.init(), msgpack-c's own reset, which also calls the visitor's init (renamed from reset). For valid input it is a no-op.

Npy has a different problem in the same setting: it keeps its row counter across inputs, so the second Npy entry of a batch is dropped; not addressed here.

The new test covers a truncated scalar, a type error inside an array and a truncated array: on master it gives a wrong row, a rejected row and an abort; with the fix it passes 50/50 with randomized settings.


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

Version info

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

groeneai and others added 2 commits November 3, 2026 11:03
StreamingFormatExecutor reuses one input format for many small inputs
(entries of one async insert batch, Kafka/RabbitMQ/NATS messages, FileLog
chunks) and calls resetParser() between them, also after a parse error.
MsgPackRowInputFormat::resetParser() reset only the visitor's info_stack,
not the msgpack-c parser (parse_helper), which is resumable by design and
keeps m_cs, m_trail and m_stack when an object is cut short by EOF or by a
visitor exception. The next input was then parsed as the continuation of
the broken object:

- a truncated array made end_array_item() dereference the empty
  array_size of column 0: LOGICAL_ERROR abort in debug builds, a libc++
  hardening abort in release builds;
- a truncated scalar consumed the next input's bytes as the rest of the
  value (four rows 1,2,3,4 became one row 16909060);
- a type error inside an array made the next valid input fail too.

resetParser() now calls parser.init(), msgpack-c's own reset, which also
calls the visitor's init() (renamed from reset(), the name msgpack calls).
For valid input this is a no-op: a complete object always leaves the
parser in its header state with an empty stack.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Name parse_helper::init as f, not f(), per the in-tree style rule.

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

groeneai commented Nov 3, 2026

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

Pre-publication review by an independent model (engine: codex; 0 findings; 1 full pass), plus my own cold review of the diff (1 nit).

# Sev Finding Verdict Evidence / action
1 💡 Function names written as f() in the new header comment (MsgPackRowInputFormat.h:55) and the commit message AGREE, noted (not blocking) Style only; header comment fixed in the publish trim commit

Checked and not raised: the fix resets all of msgpack-c's cross-call parser state (m_cs, m_trail, m_stack); every streaming caller (async inserts, Kafka, RabbitMQ, NATS, FileLog) goes through StreamingFormatExecutor, which calls resetParser on every exit path; each of the three test arms fails on master. A truncated Map is the same stale-stack case as the truncated array and is fixed by the same line.

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

Session id: cron:clickhouse-review-slot-8:20261103-111500

@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05493_msgpack_async_insert_after_invalid_entry: each arm queues an invalid and a valid HTTP async insert into one batch (100 s busy timeout + explicit SYSTEM FLUSH ASYNC INSERT QUEUE), so the batch is fixed. Fails on every run without the fix.
b Root cause explained? StreamingFormatExecutor reuses one format for all inputs of a batch and calls resetParser() between them. MsgPackRowInputFormat::resetParser() reset the visitor but not the msgpack-c parse_helper, which keeps m_cs, m_trail and m_stack when an object is cut short, so the next input was parsed as its continuation.
c Fix matches root cause? Yes. resetParser() calls msgpack-c's own parser.init(), completing the reset contract at its MsgPack implementation. No guard at the abort site.
d Test intent preserved / new tests added? New test, three arms, one per stale component: truncated scalar (m_cs/m_trail), type error inside an array (exception path), truncated array (m_stack).
e Both directions demonstrated? Without the fix: one wrong row 16909060, the valid row rejected, server abort (info_stack.top().array_size.has_value()). With the fix: passes, 50/50 with randomized settings. Also reproduced on the official 26.10.2.103 image.
f Fix is general across code paths? One reset covers both throw paths (EOF, visitor exception) and every streaming caller (async inserts, Kafka, RabbitMQ, NATS, FileLog). The other formats with a resumable parser already reset or rebuild it per input (ProtobufList, Protobuf, Avro, CapnProto).
g Fix generalizes across inputs (params/datatypes/wrappers)? The reset is type-independent. Checked locally in both directions: Map (a second abort signature on master), String, Nullable, LowCardinality(Nullable(String)), nested Array.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. A complete object always leaves the parser in its header state with an empty stack, so init() is a no-op for valid input; invalid inputs are rejected as before.
i Invariants and contracts preserved? After resetParser() the next row starts a top-level object from a clean state. Inside one input the parser stays resumable (readObject unchanged). parser.init() still clears info_stack through MsgPackVisitor::init().

Session id: cron:clickhouse-impl-slot-4:20261103-104700

@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @PedroTadim @Avogar, could you review this and add the can be tested label so CI runs? MsgPackRowInputFormat::resetParser reset only the visitor and not the msgpack-c parser, so after a truncated input the next async insert entry or Kafka message was parsed as its continuation (server abort, wrong row or rejected row); it now calls parser.init.

@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c84c72b]

Summary: ✅


AI Review

Summary

Reviewed PR #128943 at c84c72b9ca0fee3090db559cd54186eb2bbb4fd1. The change resets msgpack-c's parser and the ClickHouse visitor between streamed MsgPack inputs, preventing malformed inputs from corrupting subsequent asynchronous inserts or streaming messages. No actionable findings.

Missing context / blind spots
  • ⚠️ The regression test was not run locally because this checkout has no ClickHouse binary or build. The added test covers truncated scalars, visitor exceptions, and truncated arrays; the author reports failures without the fix and 50 passing randomized runs with it.
Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 3, 2026
@Avogar Avogar self-assigned this Nov 3, 2026
@Avogar Avogar added the can be tested Allows running workflows for external contributors label Nov 3, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). label Nov 3, 2026
@PedroTadim PedroTadim added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Nov 3, 2026
@PedroTadim
PedroTadim enabled auto-merge November 3, 2026 12:39
@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c84c72b9c with master ca06fcaaf (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 244a01454; 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

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

Job report

@PedroTadim
PedroTadim added this pull request to the merge queue Nov 3, 2026
Merged via the queue into ClickHouse:master with commit 77c29e3 Nov 3, 2026
365 of 367 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 3, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added pr-synced-to-cloud The PR is synced to the cloud repo pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Nov 3, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 3, 2026
Backport #128943 to 26.8: Reset the MsgPack parser between streamed inputs
clickhouse-gh Bot added a commit that referenced this pull request Nov 3, 2026
Backport #128943 to 26.9: Reset the MsgPack parser between streamed inputs
clickhouse-gh Bot added a commit that referenced this pull request Nov 3, 2026
Backport #128943 to 26.10: Reset the MsgPack parser between streamed inputs
PedroTadim added a commit that referenced this pull request Nov 4, 2026
Backport #128943 to 26.3: Reset the MsgPack parser between streamed inputs
alexey-milovidov pushed a commit to bobrik/ClickHouse that referenced this pull request Nov 13, 2026
…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]>
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

5 participants