Skip to content

Require forward progress when counting rows in Avro - #116156

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:avro-count-forward-progress
Sep 20, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:avro-count-forward-progress

Conversation

@groeneai

@groeneai groeneai commented Aug 24, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115437
Related: #115884

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 an Avro file with a corrupted block header. The optimize_count_from_files fast path took the row count from the header without reading the payload, so a negative declared count looped forever and an inflated one reported rows the file does not hold.

Description

Split out of #115884 at @ PedroTadim's request. Reported in #115437.

IRowInputFormat::read() re-enters countRows() until it returns 0, and AvroRowInputFormat::countRows took the 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. A header declaring 10^9 rows returned 1000005000 rows from a 34KB file as a successful answer, so nothing alerted the user.

Two changes:

  • contrib/avro is bumped to pick up Reject a data file block header declaring a negative count avro#33, which rejects a block header declaring a negative object or byte count and hardens hasMore() to test > 0. This is the layer that owns the header, so it also covers the Iceberg manifest deserializer, and it fixes the negative-count hang on a record whose fields encode to zero payload bytes, which no ClickHouse side change reached.
  • supportsCountRows() stays false, so count queries take the read path. A non-negative but inflated count is indistinguishable from a real one at the header, and the library has no accessor for the block extent, so nothing on this side can bound it.

Cost on valid files, medians of 9 interleaved runs on 30M rows snappy, debug build, two binaries differing only in the shortcut: 1.49s with it, 2.44s without. The row-count cache still applies, because StorageFile populates it on the ordinary read path too.

Still not terminating: a record whose fields all encode to zero payload bytes, with a positive corrupted count. The payload is legitimately empty, so neither the header nor the reader can tell that count is wrong.

Refuted alternatives and validation

Bounding the declared count by the remaining input size is refuted by measurement: valid Avro holds 1000 rows in 139 bytes with an all-NULL column, and 200000 rows in 810 bytes with deflate. Both are test arms here, so the design cannot be reintroduced silently.

A central guard in IRowInputFormat::read() is refuted too: Npy and RawBLOB legitimately return rows consuming zero bytes.

supportsCountRows() has exactly one caller, IRowInputFormat.cpp, so removing the override has no other reachable consumer. AvroConfluentRowInputFormat is a separate IRowInputFormat subclass that never declared it and is unaffected.

04947_avro_count_from_files_forward_progress.sh asserts error codes on a bounded run, never elapsed time. The same file on three binaries: this tree passes; without the submodule bump 12 lines differ, including all four header diagnostics; with the bump and the shortcut restored 2 lines differ, the inflated count still answering 1000005000.

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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3eeface]

Summary: ✅


AI Review

Summary

This PR removes the Avro countRows() shortcut and bumps contrib/avro so corrupted negative block-header counts are rejected in the library before SELECT count() can loop on them. I did not find a new correctness, safety, or compatibility issue in the current diff: the changed AvroRowInputFormat path still goes through the ordinary row reader, prepareReadingFromFormat guarantees a non-empty physical header for count-only reads, and the new stateless test covers the regression cases the PR claims to fix.

Missing context / blind spots
  • ⚠️ The only CI artifact currently attached to this PR is Build profile diff; I did not have stateless or integration job results to confirm 04947 on CI.
  • ⚠️ No local clickhouse-local binary was available in this workspace, so I could not rerun the new test or an Avro repro locally.
Final Verdict

✅ No new findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.20% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 2/2 (100.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 24, 2026
@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 24, 2026
@groeneai
groeneai requested a review from PedroTadim August 24, 2026 17:08
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3eeface92 with master ed4df189f (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 04971e144; 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.96 MiB 706.92 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

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

Median compile-time ratio to the baselines is ×1.07 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +2.6 s (+5%) in total before that adjustment.

Job report

@PedroTadim PedroTadim self-assigned this Aug 25, 2026
ClickHouse/avro#33 rejects a data file block header declaring a negative
object or byte count, and hardens hasMore() to test > 0 instead of != 0.
That removes the non-termination on a negative declared count at the layer
that owns the header, so termination no longer depends on the caller asking
before it decrements.

The test asserts the error class instead of one message, because the
rejection can now come either from the library at the block header or from
the read path when the payload runs out. It gains a negative declared byte
count case, which the existing fixtures could not reach because the block
helper hardcoded a byte count of zero.

A block with a corrupted declared count is also a block that runs out of
input, so the class assertion alone cannot tell the header check from
payload exhaustion. Both negative counts therefore also assert the header
diagnostic by name, on both settings.

Measured on this tree, the same test file on three binaries:
  - with the bump and no count shortcut: passes.
  - without the bump: 12 lines differ, including all four header
    diagnostics and the negative object count reaching the query deadline.
  - with the bump and the count shortcut restored: 2 lines differ, the
    oversized declared count still answering 1000005000 from the header.
@clickhouse-gh clickhouse-gh Bot added manual approve Manual approve required to run CI submodule changed At least one submodule changed in this PR. labels Aug 25, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). label Sep 4, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit 0f9590e Sep 20, 2026
182 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 20, 2026
azat pushed a commit to azat/ClickHouse that referenced this pull request Oct 5, 2026
…unded

`optimize_count_from_files` had its Avro fast path removed in ClickHouse#116156, not
guarded: `AvroRowInputFormat::countRows` sums `objectCount_` out of each block
header and skips the payload, so it could not tell a declared count from the
rows actually present. The state needed to bound it (`objectCount_`,
`blockStart_`, `blockEnd_`) is private in `api/DataFile.hh` with no accessor, and
the pin that PR shipped, `f2d65e15a324`, rejects only a negative count. A
positive count larger than the payload could hold was still accepted at the
header and answered verbatim: 10^9 declared objects over 0 payload bytes
returned 1000005000 rows from a 34 KB file, exit 0.

`ClickHouse/avro` `c488095932fb`, a direct child of that pin, closes it in the
only place that can. `readHeader` walks the schema once for a lower bound on the
bytes a single record can encode to, and `readDataBlock` rejects a block whose
declared object count cannot fit in the payload it actually has: `byteCount` for
`NULL_CODEC`, `uncompressed.size()` for `SNAPPY_CODEC`, which is decompressed
eagerly. Every case the bound cannot determine returns 0, which disables the
check, so it can only fail to reject and never falsely reject a legitimate file.

So this reverses the two removal hunks and bumps `contrib/avro` to that commit.
Neither half is correct alone: the revert alone reintroduces the invented count,
and the bump alone changes nothing for count queries. The bound lives in
`readDataBlock`, which `hasMore` drives for the count shortcut and for the
ordinary read path, so no setting bypasses it.

Measured on three binaries differing only as stated, 30M rows, snappy, 155 MB,
11 interleaved runs each: 1.541 s with the shortcut against 2.389 s without,
medians, both answering 30000000. Counts on valid input are identical to
master's on all four codecs ClickHouse can write, including the two files a
naive size bound would destroy (1000 rows in 139 bytes with an all-NULL column,
200000 rows in 810 bytes with deflate).

Residual, and the upstream author's documented tradeoff: zstd and deflate
decompress lazily, so the payload size is unknown where the bound is applied,
and a schema whose records can encode to zero bytes disables the bound for any
codec. `optimize_count_from_files = 0` remains the opt-out for both.

Test 04947 gains the bound's own diagnostic for the two covered codecs at both
settings, valid-input counts on all four codecs, and the lazily decompressed
arms. Every pre-existing reference cell is byte-identical. The new arms fail
without the revert, and also with the revert on the old pin, so they pin the
submodule bump rather than only the source change.
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.). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai manual approve Manual approve required to run CI pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants