Repository navigation
Require forward progress when counting rows in MsgPack and ProtobufList - #115884
Conversation
…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.
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 ❌ BlockersNone.
|
|
Workflow [PR], commit [b9cb1e3] Summary: ✅
AI ReviewSummaryThis PR fixes the Final Verdict✅ Approve LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 23/25 (92.00%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260821-233700 |
|
The mechanism is right and I took the narrowing half.
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 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 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. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units8 translation units recompiled, 12 s compile time in total, 8 of them have a recent master baseline. |
CI finish ledger for 1639383Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260822-060000 |
| return false; | ||
| } | ||
|
|
||
| size_t AvroRowInputFormat::countRows(size_t max_block_size) |
There was a problem hiding this comment.
@groeneai won't this create a performance degradation? We should always have the quick count path if possible
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
@groeneai let's leave the Avro fix into another PR. Don't forget to update this PR description.
There was a problem hiding this comment.
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.
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.
Related: #115437
Related: #116156
Changelog category (leave one):
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 corruptedMsgPackorProtobufListfile. Theoptimize_count_from_filesfast path counted rows without requiring the read position to advance, so a two byteProtobufListfile 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-enterscountRows()until it returns 0, so acountRows()that reports a row without consuming input never terminates. Two formats did:readFieldNumber's result, which is false without consuming once the envelope message ends, whilereader->eof()only reports the underlying buffer. Now honoured, throwing the read path's ownPROTOBUF_BAD_CASTat the same guard.parse_helper::execute'sparse_returnenum as a bool, soPARSE_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).countRowsalso discardedreadObject'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: itscount()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_errorthrows beforeexecute()can return-1, and noMsgPackVisitormethod returnsfalse, so neither error status is reachable with that visitor. Verified by measurement.A central guard in
IRowInputFormat::read()was refuted by measurement:NpyandRawBLOBlegitimately 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,MySQLDumpandRowInputFormatWithNamesAndTypeslook similar when read but consume or throw on every input tested.Read path identity: order independent oracles (
count()plussum(cityHash64(...)), sorted rows,DESCRIBE) atmax_block_size1 / 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 returned334with exit 0 on a partial row, and it is now rejected.New test
04946_count_from_files_forward_progress.shasserts 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 threeoptimize_count_from_files = 1arms. Themsgpack protobufsuites give an identical per test verdict list before and after.Workflow [PR]
Sync PR [sync-upstream/pr/115884]