Repository navigation
Restore the Avro count shortcut for snappy and bump contrib/avro to bound the declared block count - #121211
Conversation
…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.
`04947_avro_count_from_files_forward_progress` asserted the restored shortcut only through cells that the ordinary read path satisfies as well, so no cell reddened when `supportsCountRows` returned false while the `contrib/avro` bump was kept. The shortcut is answer-preserving on well-formed input by construction, so the one input class that distinguishes it is a block whose header is honest but whose payload cannot be decoded: `countRows` answers from `objectCount_` without decoding it, and a full read decodes it and throws. The new fixture appends to `ok.avro` a block declaring 2 objects in 8 payload bytes and fills those bytes with `0xff`, an unterminated varint no decoder can consume. The writer schema is `n Int64, s String`, so `minEncodedBytesPerRecord_` is 2 and `checkObjectCountFitsPayload` asks `2 > 8 / 2`, which is false: the header is accepted, so the arm exercises the count path rather than the size bound added by the bump. With `optimize_count_from_files = 1` the count is therefore 5002, and with `optimize_count_from_files = 0` the read raises `AVRO_EXCEPTION`. Measured against a binary carrying the bump and not the two source hunks: every pre-existing cell still matches its expectation, and the 5002 cell is the only one that fails.
The bound `ClickHouse/avro` c488095932fb added is only as strong as the size `readDataBlock` hands it, and that size is a materialized one for exactly one codec. For `snappy` the argument is `uncompressed.size()`, taken after the length check and the CRC-32 comparison, so it cannot lie. For the null codec it is the `byteCount` decoded from the same corrupted header the object count came from, so inflating both fields passes the check; `zstandard` and `deflate` decompress lazily through a filtering stream and are never checked at all. `countRows` iterates once per declared object and consumes no payload, so on those three codecs the file chooses how much work `count()` does: a 34 KB uncompressed file declaring 10^9 objects in 2*10^9 payload bytes passes the bound and then spends 4.7 s counting phantom rows, where the ordinary read path rejects it in 0.4 s, and at a small `max_block_size` it runs to the query deadline instead. That is the same defect class as issue ClickHouse#115437, which is why the shortcut is now taken only where the check is real. The gate belongs in `supportsCountRows()`, not in a 0 returned from `countRows()`: `IRowInputFormat::read()` reads a 0 from `countRows` as end of input, so that spelling would make `count()` answer 0. The codec name comes from `metadata()`, which `readHeader()` fills from the `DataFileReaderBase` constructor, so it is populated before `init()` and before any read. The library keeps `AVRO_CODEC_KEY` and `AVRO_SNAPPY_CODEC` file-local, hence the literals here. An absent key is the null codec by `readHeader()`'s own logic, so returning false for it is correct rather than a fallback. The test gains the snappy twin of `badpayload.avro`, where the shortcut survives and still answers 5002 from the block headers, the jointly inflated header that defeats the declared-size check, and a decline arm asserting that the other three codecs reach the read path at both settings.
Internal second-model review: 16 findings adjudicated over 5 rounds (8 agreed and fixed, 1 agreed and left to the library, 7 disagreed with evidence)An independent cold review of the resulting code plus five second-model gate passes, adjudicated against the recorded measurements. One line per finding. Blockers, agreed and fixed
Agreed, and left to the library
Blockers, disagreed with evidence
Major, disagreed with evidence
Nits
Session id: cron:clickhouse-review-slot-8:20260920-155100 |
Pre-PR validation gate (click to expand)
|
|
Workflow [PR], commit [1d90d40] Summary: ✅
AI ReviewSummaryThis PR restores the Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit 1d90d40.
Changed lines: Changed C/C++ lines covered: 9/9 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units32 translation units recompiled, 188 s compile time in total, 32 of them have a recent master baseline. |
The flaky check runs every test under ThreadFuzzer (`ci/jobs/scripts/clickhouse_proc.py`, `enable_thread_fuzzer_config`), which forces a `sched_yield` at every `pthread_mutex` lock and unlock, sleeps up to 10 ms at 0.1% of them, and sleeps up to 100 ms every 1 ms of CPU. Injected latency therefore scales with the number of synchronization points a query crosses, not with instrumentation overhead. `04947_avro_count_from_files_forward_progress` had exactly one query out of scale with the rest: the block-size sweep read a 5000-row file at `max_block_size = 1`, so 5000 one-row chunks, each a pipeline handoff. Measured on a debug build, that query costs 6878 voluntary context switches against 105 to 145 for every other query in the file, and 0.34 s of CPU against 0.12 s. It was the only cell anywhere near the test's own 30 s `max_execution_time` belt, and on `5dd3ab5b24a1c` it crossed it in 12 of about 165 flaky-check runs: 7 under `amd_asan_ubsan`, 3 under `amd_binary`, 2 under `amd_debug`, every failure within 0.14 s of the limit. `amd_binary` carries no sanitizer, and `amd_msan` and `amd_tsan` passed 55 of 55, which is what a latency-injection mechanism looks like rather than a slow build. So cut the work instead of the assertion: the shared fixtures shrink from 5000 to 500 rows, and each group of queries that must all succeed now runs in one `clickhouse-local` invocation. The sweep's sync traffic drops to 875 context switches for all three block sizes together, the 30 s belt is untouched, and 15 process launches disappear, which also keeps the test well clear of the flaky check's 180 s per-test ceiling (`TEST_MAX_RUN_TIME_IN_SECONDS`). Local runtime falls from 9.8-10.2 s to 6.8-7.1 s. Every oracle is preserved, and measured to be: 20 of 20 runs pass on the fix, a build with the codec gate dropped still reddens exactly the three `optimize_count_from_files = 1` cells of the declined arm and nothing else, and pristine master still fails. A query that dies inside a batch takes the remaining lines of that batch with it, so a regression still reddens the reference diff.
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
| # The bound is derived from the schema, not from the input size, so a file that legitimately holds | ||
| # more rows than it has payload bytes must still count. These are the files it could destroy. | ||
| echo '--- valid input on every codec counts the same with and without the count shortcut' | ||
| for setting in 1 0; do |
There was a problem hiding this comment.
Done in 64203e2: 218 -> 175 lines, reference 54 -> 41, nine arms down to six, comment prose 49 lines -> 29.
What went, and why:
- The
a corrupted block header is rejected instead of countedarm. Each of its three fixtures is already asserted at both settings by a stronger message-specific oracle (object count in block header,byte count in block header,in block header cannot fit in). This one was pre-existing rather than mine, so say the word if you would rather I put it back. - The two valid-input arms had identical loops and identical bare-count oracles, so they are now one arm covering all six valid fixtures on all four codecs.
a jointly inflated header is rejected, not countedfolded intothe shortcut is declined where the declared payload size is not verified: same exception at both settings, andinflated-bothis a null-codec file, so it is an instance of that scenario rather than a separate one.
No scenario and no codec dropped. Re-verified both directions on the merged build: 3/3 runs match the reference, the mutation binary with the codec gate dropped still reddens (now in the merged declined arm), and pristine master still reddens the size-bound arm and loses the header-only count.
One further lever if you want it smaller still: the two python fixture helpers duplicate a varint loop and could collapse into one helper with a codec argument, roughly 12 lines. I kept them separate because two obvious builders read better than one branchy one, but your call.
Merging is still blocked on the explicit bound in ClickHouse/avro, not on this file.
Three reductions, no scenario and no codec dropped: - Remove the "a corrupted block header is rejected instead of counted" arm. Each of its three fixtures is already asserted at both settings by a strictly stronger message-specific oracle: negative and negbytes by the arm that greps "object count in block header" and "byte count in block header", huge by the arm that greps "in block header cannot fit in". - Merge the two valid-input arms, which had identical loops and identical bare-count oracles, into one arm covering all six valid fixtures on all four codecs. - Merge "a jointly inflated header is rejected, not counted" into "the shortcut is declined where the declared payload size is not verified". Both assert the same exception at both settings, and inflated-both is a null-codec file, so it is an instance of that same scenario rather than a separate one. Comment prose goes from 49 lines to 29, keeping only what the code does not state: the snappy block framing, the row ceiling the flaky check's thread fuzzer imposes, why an all-NULL column defeats an input-size bound, and why null, deflate and zstd are not payload-checked. The test goes from 218 to 175 lines and the reference from 54 to 41, so the diff against master shrinks from +148/-36 to +112/-43 on the .sh. Verified both directions on the merged build, build-id 25dc656ffd6a10ea1125a694b2ee7b54196822cb: 3/3 runs match the reference; the mutation binary with the codec gate dropped still reddens, now in the merged declined arm, and pristine master still reddens the size-bound arm and loses the header-only count.
| if (it == metadata.end()) | ||
| return false; | ||
|
|
||
| return std::string_view(reinterpret_cast<const char *>(it->second.data()), it->second.size()) == "snappy"; |
There was a problem hiding this comment.
@groeneai why the shortcut only works for the snappy codec?
There was a problem hiding this comment.
The shortcut answers from the block header, so it is only sound where the library bounds the declared object count against the block's real payload. In the bumped pin, readDataBlock reaches that bound from exactly two places, and only one of them gets an argument the header cannot fabricate:
DataFile.cc:590, snappy:checkObjectCountFitsPayload(uncompressed.size()), after eager decompression, thelen < 4check and the CRC-32 comparison. A real size, verified, and known before the first row is reported.DataFile.cc:539, null: the argument is the header's own declaredbyteCount, so a file that inflates both fields satisfies the bound by construction.- zstd (
:542) and the deflate else-branch (:600) never reach it: both wrap the payload in a lazily decodingfiltering_istream, so no decoded size exists at header time.
Re-measured today, this PR's binary against the same binary with only the codec gate dropped, optimize_count_from_files = 1:
| file | this PR | gate dropped |
|---|---|---|
huge-zstd.avro |
AVRO_EXCEPTION, 0.29 s | 1000005000, exit 0 |
huge-deflate.avro |
AVRO_EXCEPTION, 0.30 s | 1000200000, exit 0 |
badpayload.avro, null |
AVRO_EXCEPTION | 5002 |
inflated-both.avro, null, 10^9 objects declared in 2 * 10^9 payload bytes with none supplied |
error in 0.28 s | error in 4.73 s, and Code: 159 timeout at max_block_size = 1 |
badpayload-snappy.avro |
5002 |
5002 |
The first two rows are the decisive ones: a wrong count at exit 0, not an error. Those same three top rows are the cells that pin the gate in 04947.
The gate is as wide as the library's guarantee rather than as wide as it could be, and widening it belongs in ClickHouse/avro:
- null: bound against the bytes the block actually yields instead of the declared
byteCount, which also removes the burn in row 4. - zstd/deflate: the decoded size exists only after decompression, so either decompress eagerly as snappy does, or check once the block is drained, which turns the wrong count into an error but keeps the phantom decrements.
I can prepare either one there and drop the gate here once the bound covers the codec. Leaving it as is, my reasoning is that restoring the shortcut where the bound already holds beats widening it on a promise, but it is your call.
… force Two defects in c488095, both reported on ClickHouse/ClickHouse#121211. The walk had no memoisation. A schema is a DAG: one field can inline a type that another field names, so both arms reach the same node and the work doubles per level. It runs from readHeader(), i.e. in the reader's constructor, before a caller can reject the file for any other reason. On a schema that names each next level twice, reader construction took 0.028 / 0.109 / 0.437 / 1.75 / 28.3 s at depth 20 / 22 / 24 / 26 / 30. It is now 0.2 ms at each of those, and at depth 40. Memoising by resolved node identity, with the on-path set as a cycle guard, also removes the need for the depth cap - and that cap was the second defect. Past 64 levels the walk returned 0, which disables checkObjectCountFitsPayload entirely. A 10-object snappy file with a second block declaring 10^9 objects over the same payload was rejected at depth 60 and 64 but accepted at 65 and 80; all four are rejected now. ClickHouse allows schemas up to 256 levels, so this was reachable. Zero is still returned wherever no usable bound can be derived, but it is no longer the caller's only signal: checksDeclaredObjectCount reports whether this reader cross-checks a block's declared object count at all. A caller answering a row count from block headers alone needs exactly that, and cannot derive it - a bound recomputed outside the library can be positive where this one is zero, and the codec string is a different condition. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The only conflict was the `contrib/avro` gitlink. Both sides moved it off the `f2d65e15a324` pin in opposite directions: master to `6640c55c752e` (avro ClickHouse#35, close on empty manifest), this branch to `c488095932fb` (avro ClickHouse#34, bound the declared object count by a schema-derived minimum record size). Resolved to `d90416ad4a58`, the current `ClickHouse/avro` master, which is the merge of the two: `57985a1d` merges ClickHouse#34 on top of ClickHouse#35, and `d90416ad` adds `61d47507`, the `DataFileTests.cc` fix that ClickHouse#34's new cross-check requires. Nothing else is in that range, so this pulls in neither side's change twice nor anything unrelated. Related: ClickHouse#121211 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
@groeneai also bump the avro submodule here. Is the issue not fixed yet? |
ClickHouse/avro#36 memoises the minimum-encoded-size walk instead of cutting it at 64 levels, and adds `checksDeclaredObjectCount`, which is true only when every block's declared count is checked against a decoded payload size: snappy, with a schema whose records cannot encode to zero bytes. `supportsCountRows` now asks that instead of comparing the codec name, so the condition lives next to the check it depends on. On the previous pin, a snappy file whose schema nests more than 64 records and whose block declares 10^9 objects in 8 bytes counted 1000000010 with optimize_count_from_files = 1; it is now rejected at the block header with both settings. The test gains that case at depth 65. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Bumped Yes, it is fixed now. Both defects the description listed were in
I also made With schema inference, the 40-level file still times out, because ClickHouse expands that schema into a tree of types. Master does the same with its pin, which has no such walk, so this is not in avro. |
`Stateless tests (amd_tsan, flaky check)` failed 04947 on every run: the
fixture `deep-snappy.avro` was written from 65 nested `tuple()` calls, and
the analyzer resolves those recursively. Under TSan `checkStackSize` allows
only a small fraction of the stack, and the 65th level crosses it
(`TOO_DEEP_RECURSION`, ~424 KB used), so the file was never written and the
two `huge-deep-snappy.avro` cells read a missing file.
`defaultValueOfTypeName('Tuple(Tuple(...UInt64))')` produces the same
column type with no expression nesting. The Avro schema it writes is
byte-identical to the old one (sha1 of `avro.schema` matches), so the cell
still exercises a record nested past the old 64-level walk cap. The type is
parsed with `DataTypeFactory`'s fixed parse depth of 150, which this depth
stays under on every build (75 levels is the first that is refused).
Verified with the CI TSan binary of c0cbf61: the old test reproduces
the CI diff (MISSING FIXTURE huge-deep-snappy.avro), the new one passes
19/19 including 8 parallel copies (~20 s each). It still fails on the
previous pin d90416a at exactly the two deep cells, and on the
`supportsCountRows` mutation, so the cell keeps its discriminating power.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The count shortcut keeps a partially counted block between `read()` calls, but no cell of the test ever stopped a count inside a block: `ok-snappy.avro` was a single 500-row block and every shortcut-enabled count used the default `max_block_size`. Write that fixture as three blocks (200, 171, 129 rows with `output_format_avro_sync_interval = 1024`) and count it at `max_block_size = 7`, so chunks end inside a block and straddle block boundaries. A mutation that drops the rest of a partially counted block passes the previous test and fails this cell (21 instead of 500). The other cells that read `ok-snappy.avro` keep their expected values. The new query adds about 60 voluntary context switches, against about 740 for the existing `max_block_size = 1` read of `ok.avro`, so it stays clear of the flaky check's thread fuzzer budget. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - b90ed3dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Neither touches the Avro/MsgPack/ProtobufList row counting this PR changes, and all five stateless flaky checks passed on this head. All 160 checks completed; CIDB has no other Session id: cron:our-pr-ci-monitor:20261003-173335 |
|
Fixing PR for 05237_with_expression_alias_scope_descendant (DBReplicated): #123774 |
Keep only the recursive record (fails building the datum) and the 1,000,000-level nullable cycle (fails reading it), and assert which of the two ClickHouse/avro#39 depth checks fires, with its error code. Drop the controls and the server liveness probe; the test uses only `clickhouse local`. The contrib/avro bump is no longer part of this PR: master already pins the same commit since ClickHouse#121211. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@groeneai @PedroTadim — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
…out recursion Since ClickHouse#121211, `readHeader` in contrib/avro runs `MinEncodedBytesWalker` on every Avro read to bound the declared object count. It recursed through every record field and union branch, following named references, so a schema chaining 100000 named records, each defined inside an array field, overflowed the thread stack while the header was parsed. ClickHouse/avro now walks the schema with its own stack on the heap, in the same order and with the same memo and cycle cut, so the bound does not change for any schema. The test generates such a file and reads it with an explicit structure. The test also checks that the chain still bounds a block's declared object count. Reported in ClickHouse#123998. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #115437
Related: #116156
Related: #121201
Related: #123084
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
SELECT count()oversnappy-compressedAvrofiles uses the block header row count again instead of decoding every row, which is 1.55x faster on 30M rows. The shortcut was removed in #116156 because a block header could declare more rows than its payload holds; the bundledClickHouse/avronow rejects such a count wherever it can derive a lower bound for the schema.Description
Restoring the fast path @ PedroTadim asked for in #115437, for the codec where the new bound is real.
#116156 removed
AvroRowInputFormat::supportsCountRows/countRowsinstead of guarding them: the pin it shipped rejects only a negative declared count.ClickHouse/avromaster (a56fc2f95d18, with ClickHouse/avro#34 and #36) also rejects a count that cannot fit in the payload the block carries. This PR reverses those two hunks, bumpscontrib/avroto it, and takes the shortcut only where the library reports that check is in force (checksDeclaredObjectCount):snappy, ClickHouse's default output codec, whose decoded size is CRC-verified before the first row, with a schema whose records cannot encode to zero bytes. Fornullthe check compares two fields of the same corrupted header, anddeflate/zstandarddecompress lazily, so those keep the read path.The bump also carries ClickHouse/avro#39: a
GenericDatumnested deeper than 256 levels now throws instead of overflowing the stack. Only the Iceberg manifest code buildsGenericDatum, and #123084 tests that path.Validation:
04947_avro_count_from_files_forward_progress(6 arms, 500-row fixture), including a 65-levelsnappyschema declaring 10^9 objects in 8 bytes, which the previous pin counted as1000000010.Benchmark method and raw timings for the 1.55x (measured at `c488095932fb`; the count loop is unchanged)
30M rows of
{n UInt64, s String}written withoutput_format_avro_codec = 'snappy'(155,510,992 bytes), page cache warmed, thenSELECT count() FROM file(f, Avro) SETTINGS optimize_count_from_files = 1, use_cache_for_count_from_files = 0timed 11 times per arm, arms interleaved. The two binaries differ only in the two reverted hunks and the pin.cc @PedroTadim
Workflow [PR]
Sync PR [sync-upstream/pr/121211]
Version info
26.10.1.1559-master(included in26.10and later)