Skip to content

Require forward progress when counting rows in MsgPack and ProtobufList - #115884

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:countrows-forward-progress
Aug 25, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:countrows-forward-progress

Conversation

@groeneai

@groeneai groeneai commented Aug 22, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115437
Related: #116156

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 SELECT count() never terminating, or returning an invented row count, on a corrupted MsgPack or ProtobufList file. The optimize_count_from_files fast path counted rows without requiring the read position to advance, so a two byte ProtobufList file produced billions of rows and never returned. Such input is now rejected with the same error the ordinary read path gives.

Description

Reported by @ PedroTadim, who offered to review; I took it.

IRowInputFormat::read() re-enters countRows() until it returns 0, so a countRows() that reports a row without consuming input never terminates. Two formats did:

  • ProtobufList discarded readFieldNumber's result, which is false without consuming once the envelope message ends, while reader->eof() only reports the underlying buffer. Now honoured, throwing the read path's own PROTOBUF_BAD_CAST at the same guard.
  • MsgPack treated parse_helper::execute's parse_return enum as a bool, so PARSE_PARSE_ERROR (-1) left the loop as if it had succeeded, offset unadvanced. Each status is now handled; the read path is unaffected (details below). countRows also discarded readObject's result, counting a partial row as complete when the object count is not a multiple of the column count; it now raises the read path's own "Not enough values to complete the row".

The third format in the report, Avro, is split out into #116156 at @ PedroTadim's request: its count() shortcut reads the row count from the block header, so the fix has to drop the shortcut, and unlike these two changes that costs read time on valid files.

Sibling coverage, refuted alternatives and validation

MsgPack read path: parse_error throws before execute() can return -1, and no MsgPackVisitor method returns false, so neither error status is reachable with that visitor. Verified by measurement.

A central guard in IRowInputFormat::read() was refuted by measurement: Npy and RawBLOB legitimately return rows consuming zero bytes, so the fix has to be per format.

All 15 remaining countRows() implementations were swept empirically, 17 formats x 6 adversarial inputs: only the three reported formats hung. The same sweep prints a hang on unpatched master, so it can see what it reports absent. CapnProto, MySQLDump and RowInputFormatWithNamesAndTypes look similar when read but consume or throw on every input tested.

Read path identity: order independent oracles (count() plus sum(cityHash64(...)), sorted rows, DESCRIBE) at max_block_size 1 / 7 / 13 / 1000 / 65505, all identical before and after; 13 of 13 deliberate mutations detected, so the comparison is not blind. A 1000 object file read with a 3 column schema is the one intended difference: master returned 334 with exit 0 on a partial row, and it is now rejected.

New test 04946_count_from_files_forward_progress.sh asserts the error code on a bounded run, never elapsed time. Run against unpatched master it differs from its reference on 3 lines, and they are exactly the three optimize_count_from_files = 1 arms. The msgpack protobuf suites give an identical per test verdict list before and after.


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

groeneai and others added 2 commits August 21, 2026 20:28
…obufList

IRowInputFormat::read() re-enters countRows() until it returns 0, so a
countRows() that reports a row without consuming input cannot terminate.
Three formats could do that, and SELECT count() over a corrupted file
either ran forever or returned an invented count as a successful answer.
Only the optimize_count_from_files fast path was affected; the ordinary
read path rejected every one of these inputs cleanly.

ProtobufListInputFormat::countRows discarded readFieldNumber's result.
That function returns false without consuming anything once the envelope
message is exhausted, while reader->eof() reports only the underlying
buffer, so on a truncated message the two disagree and the loop stood
still. Honour it and throw the PROTOBUF_BAD_CAST that the read path
already throws at the same guard, so both paths agree on the error.

MsgPackRowInputFormat::readObject tested parse_helper::execute() as a
bool, but it returns the parse_return enum: PARSE_PARSE_ERROR (-1) and
PARSE_STOP_VISITOR (-2) are non-zero, so a parse error left the refill
loop as if it had succeeded with the offset unadvanced. Handle each
status. This cannot alter read path behaviour, because there
MsgPackVisitor::parse_error throws before execute() can return -1, and no
MsgPackVisitor method returns false, so neither error status is reachable
with that visitor. Only null_visitor, whose parse_error is empty, could
swallow the error, and that is the counting path. Confirmed by comparing
13 order independent oracles across both binaries.

For Avro the declared row count comes from the block header, so counting
without decoding the payload cannot tell a count that is present from one
that is merely claimed: a header declaring 10^9 rows returned 1000005000
rows for a 10KB file, and a negative count never terminated at all, since
hasMore() tests objectCount_ != 0 while decr() only decrements. There is
nothing for the fast path to validate, so supportsCountRows() is now
false for Avro and the dead countRows() is removed. Count queries take
the read path, which already rejects all of these inputs, at a measured
cost of 0.109s to 0.136s on 3M rows in 32MB.

A bound relating the declared count to the input size was rejected on
measurement: valid Avro holds 1000 rows in a 139 byte file when the only
column is NULL, and 200000 rows in 797 bytes with deflate. A single guard
in IRowInputFormat::read() was rejected too, since NpyRowInputFormat and
RawBLOBRowInputFormat legitimately report rows while consuming no bytes.
Both cases are arms of the new test.

All 15 remaining countRows() implementations were also exercised against
six adversarial inputs; none of them fails to make progress.

Closes: ClickHouse#115437

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
MsgPackRowInputFormat::countRows discarded readObject's return value while
readRow honours it. readObject returns false only when it finds EOF at entry,
so when a file's object count is not a multiple of the column count, the inner
per-column loop completed on a partial row, that row was counted, and the outer
eof test then exited normally.

SELECT count() therefore returned a row that the ordinary read path refuses:
for three objects read through a two column schema it returned 2 with exit 0,
while SELECT * threw INCORRECT_DATA "Not enough values to complete the row.".
countRows now honours the result and raises the same error, so both paths
agree. A row boundary that is clean (i == 0) still returns the rows counted so
far, which is how a well formed file ends.

The new test arm builds the fixture by construction, writing a one column
MsgPack file and reading it back with a two column schema, so it does not
depend on the encoding. Verified to fail on the parent commit and to be
attributable: reverting only this guard flips the arm back.

Also drops a false clause from the readObject comment. execute() sets the
offset and returns PARSE_CONTINUE in the incomplete-input path too, so the only
load bearing property is that both error statuses are negative and were
therefore indistinguishable from success under a boolean test.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — 2 rounds, 5 findings adjudicated (4 agreed and fixed, 1 disagreed with evidence)

Every finding below comes from an independent cold review of the resulting code plus a second-model
gate pass, adjudicated against the recorded measurements. Round 1 bounced two majors back for
implementation; round 2 found none.

❌ Blockers

None.

⚠️ Majors — agreed and fixed

MsgPackRowInputFormat::countRows still discarded readObject's result (round 1, agreed, fixed
in 1639383). readRow honours it and throws INCORRECT_DATA "Not enough values to complete the row."; countRows did not, so when a file's object count is not a multiple of the column count the
inner per-column loop completed on a partial row and that row was counted. Measured before the fix: a
3-object file read through a 2-column schema returned 2 with exit 0 while SELECT * threw. Both
paths now give Code 117. This was in scope because the changelog entry names "returning an invented
row count".

No test arm could see it (round 1, agreed, fixed). The fixtures were a single-byte parse error and
a complete file, so no input had a non-multiple object count. The new arm builds its fixture by
construction — write a one-column MsgPack file, read it with a two-column schema — so it does not
depend on the encoding. Attribution proven in both directions: it reddens on the parent commit, and
reverting only that guard (rebuilt to a distinct build id, with the revert confirmed present first)
flips the arm back.

⚠️ Major — disagreed, with evidence

"The test cannot tell whether the count fast path ran." The necessary step is that the oracle
cannot discriminate. Running the whole test against a pristine master binary flips exactly 5 of 39
reference lines, and those 5 are precisely the five optimize_count_from_files = 1 arms while every
= 0 arm already passed — so the oracle discriminates on exactly the axis in question. The proposed
remedy, asserting that the framing-only shortcut is still in use, would also have to be false for
Avro and true for the other formats, since this change deliberately removes Avro's shortcut.

Residual, noted not blocking: a future silent loss of the shortcut for MsgPack or ProtobufList would
be an untested performance regression.

💡 Nits

A comment claimed execute() advances the offset only on success (round 1, agreed, fixed).
False — the incomplete-input path sets the offset and returns PARSE_CONTINUE too. The comment now
states only the load-bearing property, that both error statuses are negative and were therefore
indistinguishable from success under a boolean test.

Dropping Avro's count shortcut makes tests/performance/count_from_formats.xml slower on the Avro
row
(round 2, agreed, no code change). Measured at 0.109s to 0.136s on 3M rows / 32MB over 9 runs
each. That is the deliberate price of not reporting a declared row count as a real one; it is stated
in the description, and pinning the shortcut is what this change removes.

@clickhouse-gh clickhouse-gh Bot closed this Aug 22, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b9cb1e3]

Summary: ✅


AI Review

Summary

This PR fixes the optimize_count_from_files fast path for MsgPack and ProtobufList so corrupted inputs now fail the same way as the ordinary read path instead of looping forever or inventing rows. I did not find a new correctness, safety, or test-coverage gap in the current head diff.

Final Verdict

✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 23/25 (92.00%) · Uncovered code

Full report · Diff report

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Five fixtures, each a printf, a 3 byte MsgPack write or a 23 byte block header append, no timing dependence. printf '\x00\x00' > bad.pb; clickhouse local -q "SELECT count() FROM file('bad.pb', ProtobufList, 'a UInt64, b Int32, c Float64, d String') SETTINGS max_execution_time=10" hits the bound on every run on unpatched master; printf '\xc1' (MsgPack), a 3 object MsgPack file read with a 2 column schema, and an Avro block declaring objectCount = -5 / 10^9 / 10^12 behave likewise.
b Root cause explained? Yes. IRowInputFormat::read() re-enters countRows() until it returns 0, so reporting a row without consuming input cannot terminate. ProtobufList discarded readFieldNumber's result, which is false without consuming past the envelope end while reader->eof() tracks only the buffer; MsgPack read parse_helper::execute's parse_return enum as a bool, so PARSE_PARSE_ERROR (-1) exited the loop as success with the offset unadvanced, and its countRows separately discarded readObject's result, counting a partial row as complete; Avro takes its count from the block header, which the fast path cannot validate without decoding the payload it deliberately skips.
c Fix matches root cause? Yes. Honour both discarded results; handle the enum the API actually returns; and for Avro remove the shortcut that cannot check what it reports rather than adding a heuristic to it. No widened bound, no no-random-* tag, no guard bolted on at a crash site.
d Test intent preserved / new tests added? Yes. No existing test weakened or deleted. New 04946_count_from_files_forward_progress.sh covers 5 negative arms under both optimize_count_from_files values, plus 5 positive controls (777 / 555 / 5000 rows, 1000 rows in a 139 byte all NULL file, 200000 rows in a 797 byte deflate file) and 2 boundary controls (0 byte and 1 byte ProtobufList still return 0). It asserts error codes on a bounded run, never elapsed time.
e Both directions demonstrated? Yes, on Build ID verified binaries (base bda92083…, fix 6b1123f9…). Base: three fixtures hit the execution bound, one returns 1000005000 from a 10KB file with exit 0, and the truncated MsgPack file returns 2 with exit 0 where the read path errors. Fix: every one gives the clean error the read path already gave, under both settings. Run against unpatched master the test differs from its reference on exactly the 5 optimize_count_from_files = 1 lines, and it passed 50 of 50 randomized runs. Attribution checked by reverting the MsgPack countRows guard alone, to a third distinct Build ID, and confirming that arm flips back.
f Fix is general across code paths? Yes for the shipped scope. All 15 remaining countRows() implementations swept empirically, 17 formats x 6 adversarial inputs: none fails to progress now, and the same sweep still prints a hang on unpatched master, so it can detect what it reports absent. Dropping supportsCountRows() removes the whole Avro count fast path rather than patching one loop inside it. readRow and the Iceberg manifest deserializer share the underlying hasMore()/decr() defect, are reachable only through a zero width schema, and are called out in the description as needing a ClickHouse/avro change first. Npy and RawBLOB legitimately return rows consuming zero bytes and are documented as must not guard, which is also why a central guard in IRowInputFormat::read() is wrong.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Declared counts negative, huge positive and zero; inputs empty, 1, 2, 4 and 64 bytes plus \x80; Avro null, deflate and snappy codecs; zero width and ordinary schemas; max_block_size 1 / 7 / 13 / 1000 / 65505. Type wrappers are not a carrier here, since this is byte level framing rather than typed values.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default changed, so no SettingsChangesHistory.cpp entry; no serialization format change, so no versioning or upgrade path. Behaviour differs only for input that previously hung or returned an invented count, and the new error is the one the ordinary read path already produced. Dropping supportsCountRows() for Avro is an internal optimization, not an interface; measured cost 0.109s to 0.136s on 3M rows in 32MB.
i Invariants and contracts preserved? Yes. readObject still returns true exactly when it consumed an object, and both callers now honour that contract identically; the PeekableReadBufferCheckpoint protocol is untouched, since the new throw unwinds it the same way the two pre-existing throws in that loop already do. Removing countRows() for Avro leaves readRow as the single row source, so the format keeps one code path instead of two that could disagree. No shared state, locks or concurrency contract involved (per format parser state only). Read path identity confirmed by 17 order independent oracles, with 13 of 13 deliberate mutations detected.

Session id: cron:clickhouse-impl-slot-7:20260821-233700

@groeneai

Copy link
Copy Markdown
Collaborator Author

The mechanism is right and I took the narrowing half.

readRow does drive hasMore()/decr() before deserializing (AvroRowInputFormat.cpp:1280-1284), so with a corrupted negative block count a zero-payload record does not terminate on either path. Measured on this head: that file times out at 25s with optimize_count_from_files 1 and 0 alike, identically on unpatched master, while negcnt.avro gives Code: 748 here and times out on master. So this is pre-existing and untouched by the PR, not a regression it introduces.

I cannot fix it ClickHouse-side, and not only for the reason you give. A valid Avro file with the same zero-payload schema holds 1000 rows in 139 bytes and still counts 1000 correctly, so requiring readRow to advance the offset would reject legitimate input. The guard has to reject the block header itself, in contrib/avro's readDataBlock, which also covers the Iceberg manifest deserializer (src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.cpp:50). I have READ on ClickHouse/avro and there is no fork to push to, and a pin the upstream remote does not serve fails the submodule check (base pin resolves there, mine resolves 0 times), so bumping it here would be a guaranteed CI red. The patch is written and held.

The changelog entry now says the zero-payload case is not covered, so the claim matches the code. I did not take your suggested wording verbatim: it drops the ProtobufList hang, which is the reporter's own two byte reproducer and is fixed here.

On the test: I am not adding that arm. It would assert an error only the submodule change produces, so it fails today for the right reason and is dead weight until then; the two zero-payload fixtures are already in the sweep. The three ERROR jobs in your summary were runner startup failures that each retried green, and the flaky check ran the new test 50 times with 0 failures.

@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b9cb1e37a with master 2797514bd (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
Binary Master PR Δ
programs/clickhouse-stripped 709.23 MiB 706.19 MiB -3.04 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger for 1639383

Every failure below has an owner: a fixing PR (ours 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 (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 04510_not_has_function_explain master-side test content, not reachable from this branch (the cited line 210 exceeds this head's 80-line copy of the file; master's copy is 403 lines, and praktika builds the merge commit) #115883 (external, open)

Session id: cron:our-pr-ci-monitor:20260822-060000

@PedroTadim PedroTadim self-assigned this Aug 22, 2026
return false;
}

size_t AvroRowInputFormat::countRows(size_t max_block_size)

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 won't this create a performance degradation? We should always have the quick count path if possible

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

You are right that it costs something, and the number in my PR body understated it. Remeasured on an official release binary (26.8.1.1977), SELECT count() over Avro, 30M rows, medians of 9 interleaved runs with the row count cache off:

  • snappy, 155 MB: 1.15s with the shortcut, 1.87s without
  • uncompressed, 378 MB: 0.20s with, 0.80s without

So roughly 20 to 25ns per row, 1.6x to 4x. Repeated counts of the same unchanged file are still served from use_cache_for_count_from_files (on by default), which the read path populates as well, so the cost is once per file version: on JSON, which already has supportsCountRows() = false exactly as Avro does after this PR, 3M rows go 0.169s then 0.004s.

I removed the shortcut rather than guarding it because Avro takes the row count from the block header and validates neither field there, and rejecting a negative count is not enough. A header declaring 10^9 rows in a 10KB file returns 1000005000 as a successful answer with the shortcut, and Code: 748 without it. Bounding the declared count by the input size does not work either, and both counterexamples are test arms in this PR: 1000 rows in 139 bytes (a single NULL column) and 200000 rows in 797 bytes (deflate). Making the declared count trustworthy means corroborating it against the block payload, which is a contrib/avro change, and I only have read access on that repository.

If you would rather keep the quick path, I am glad to narrow this PR to ProtobufList and MsgPack, where the fix is local and costs nothing, and leave Avro to a follow-up once the contrib/avro header validation lands. The Avro hang is pre-existing, so deferring it regresses nothing. Your call, and I will do whichever you prefer.

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 let's leave the Avro fix into another PR. Don't forget to update this PR description.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done: #116156 carries the Avro change, and this PR is back to ProtobufList and MsgPack only. AvroRowInputFormat here is now byte-identical to master.

Description and changelog updated accordingly, and the shared test lost its Avro arms: it still reddens on unpatched master on 3 lines, exactly the three optimize_count_from_files = 1 negative arms. The Avro arms and the two refuted-design fixtures (1000 rows in 139 bytes, 200000 in 797) moved to 04947 in the new PR, which reddens there on 2 lines and passed 50 of 50 randomized runs.

The Closes: on #115437 became Related: on both, since the issue reports all three formats and neither PR alone resolves it.

PedroTadim asked for the Avro half to live in its own pull request, since
dropping Avro's metadata-only count shortcut costs read time on valid files
while the ProtobufList and MsgPack changes are pure correctness fixes.

AvroRowInputFormat is restored to its state on master, and the test drops its
Avro arms and fixtures. The remaining arms still redden on unpatched master:
three assertion lines flip, exactly the three optimize_count_from_files = 1
negative arms.
@PedroTadim PedroTadim changed the title Require forward progress when counting rows in Avro, MsgPack and ProtobufList Require forward progress when counting rows in MsgPack and ProtobufList Aug 25, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 25, 2026
Merged via the queue into ClickHouse:master with commit baa44e7 Aug 25, 2026
178 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 25, 2026
pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Sep 20, 2026
SELECT count() over an Avro file with a corrupted block header never returned,
or returned a row count the file does not hold. IRowInputFormat::read()
re-enters countRows() until it returns 0, and AvroRowInputFormat::countRows
took the row count straight from the block header: hasMore() tests the declared
count against zero while decr() only decrements, so a negative count never
reaches it, and an inflated count reports rows that are not there.

Counting from the header cannot tell a count that is present from one merely
claimed, so the shortcut is removed and count queries take the read path, which
rejects both inputs with avro::Exception: EOF reached. The cost on valid files
is 1.15s to 1.87s on 30M snappy-compressed rows, 0.20s to 0.80s uncompressed;
the row-count cache still applies, since StorageFile populates it on the
ordinary read path too.

Bounding the declared count by the remaining input size was considered and
rejected: valid Avro holds 1000 rows in 139 bytes with an all-NULL column, and
200000 rows in 797 bytes with deflate. Both are test arms here.

One case is still open. A record whose fields all encode to zero payload bytes
makes the ordinary read path spin as well, and no change on the ClickHouse side
reaches it: hasMore() and decr() live in contrib/avro, driven by the Iceberg
manifest deserializer as well as by this format. That needs the block header
rejected in ClickHouse/avro first.

Split out of ClickHouse#115884 at PedroTadim's request.
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

3 participants