Skip to content

Restore the Avro count shortcut for snappy and bump contrib/avro to bound the declared block count - #121211

Merged
PedroTadim merged 13 commits into
ClickHouse:masterfrom
groeneai:avro-restore-count-shortcut
Oct 5, 2026
Merged

PedroTadim merged 13 commits into
ClickHouse:masterfrom
groeneai:avro-restore-count-shortcut

Conversation

@groeneai

@groeneai groeneai commented Sep 20, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115437
Related: #116156
Related: #121201
Related: #123084

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

SELECT count() over snappy-compressed Avro files 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 bundled ClickHouse/avro now 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 / countRows instead of guarding them: the pin it shipped rejects only a negative declared count. ClickHouse/avro master (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, bumps contrib/avro to 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. For null the check compares two fields of the same corrupted header, and deflate/zstandard decompress lazily, so those keep the read path.

The bump also carries ClickHouse/avro#39: a GenericDatum nested deeper than 256 levels now throws instead of overflowing the stack. Only the Iceberg manifest code builds GenericDatum, and #123084 tests that path.

Validation: 04947_avro_count_from_files_forward_progress (6 arms, 500-row fixture), including a 65-level snappy schema declaring 10^9 objects in 8 bytes, which the previous pin counted as 1000000010.

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 with output_format_avro_codec = 'snappy' (155,510,992 bytes), page cache warmed, then SELECT count() FROM file(f, Avro) SETTINGS optimize_count_from_files = 1, use_cache_for_count_from_files = 0 timed 11 times per arm, arms interleaved. The two binaries differ only in the two reverted hunks and the pin.

arm                                 median    min     max     result
with the shortcut (this PR)          1.541   1.487   1.800   30000000
without it (master)                  2.389   2.357   2.621   30000000

raw, interleaved (seconds)
this PR  1.583 1.500 1.487 1.685 1.531 1.499 1.541 1.800 1.589 1.516 1.554
master   2.389 2.394 2.371 2.621 2.620 2.377 2.415 2.357 2.403 2.389 2.364

cc @PedroTadim


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

Version info

  • Merged into: 26.10.1.1559-master (included in 26.10 and later)

…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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
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

  • "minEncodedBytes can take exponential time on a linearly sized schema." Real: the walk resolves each symbolic reference without memoising, so a schema that both inlines and names each level doubles the work per level, and the depth-64 cap bounds path length, not path count. Harmless for a record root, where avroNodeToDataTypeImpl and createAction unfold the same graph and already do strictly more per node, but not for a root that is not a record: those two reject it with Root schema must be a record before traversing, while the walk runs first, inside the DataFileReaderBase constructor. Measured on this branch, a 2,442-byte union-root file returns that same error in 0.15 s at 20 levels, 0.35 s at 22 and 1.12 s at 24, doubling per level; without the pin there is no walk, so the error is immediate at any depth. Not fixed here because it is not this side's code: the walk is ClickHouse/avro c488095932fb, memoising by resolved node identity with an active-node cycle guard belongs there, and I would take that upstream change before merging this one.

Blockers, disagreed with evidence

  • "The size bound does not make the shortcut safe: a count that merely could fit is still accepted." True, and the description says so: it is a fit check, not an equality check. What I do not accept is the remedy, that a count shortcut must prove exact correspondence or decline. optimize_count_from_files promises a metadata-derived count and every sibling does the same or less: ParquetV3BlockInputFormat answers the footer's num_rows and rejects only a negative count, NpyRowInputFormat::countRows answers header.shape[0] with no cross-check at all. What that contract does not license is unbounded WORK, which is why the jointly inflated header above is fixed rather than disclosed.
  • "Schemas deeper than the library's 64-level walk silently disable the bound" (and the same for records that encode to zero bytes). Both confirmed: minEncodedBytes returns 0 past depth 64 while ClickHouse accepts 256, and a zero minimum makes the check return early. What I refute is that declining on that basis is available here: DataFileReaderBase exposes neither the computed minimum nor a "was this block bounded" predicate, so the only ClickHouse-side substitute is re-deriving the library's schema walk, including its depth cap, in the wrong layer. With the shortcut limited to snappy it now takes a crafted file whose computed minimum is zero; that residual is in the description, and the way to close it is upstream: validate the block extent, by skipping the declared payload and confirming the sync marker, before a caller may count from the header.

Major, disagreed with evidence

  • "The schema walk suppresses resolveSymbol failures and silently disables the bound." The catch is real, but resolveSymbol throws only when a symbolic node's weak reference to its referent has expired, and in a schema parsed by compileJsonSchema the referent is owned by the same graph the reader holds for its whole lifetime, so no input file reaches that path; it is defensive code, and upstream states the fail-open policy in the function's own comment.

Nits

  • The changelog entry claimed the whole Avro format. Agreed and corrected: it now says snappy rather than promising every Avro reader a speedup.
  • The 1.55x lacked its method in the reviewed artifact. The command and all 22 raw timings are in the collapsed block in the description; the figure is a snappy measurement, so limiting the shortcut to that codec does not touch it.

Session id: cron:clickhouse-review-slot-8:20260920-155100

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Sep 20, 2026
@clickhouse-gh clickhouse-gh Bot closed this Sep 20, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, no randomization and no timing dependence. Five build-id-verified binaries differing only as stated: A pristine master, B master + the restored shortcut on the old pin, C revert + bump without the codec gate, D the bump without the two source hunks, E this PR. On a null-codec file whose appended block header declares 10^9 objects in 0 payload bytes, B answers 1000005000, exit 0, on every run; E rejects it at both settings. The one fixture that is not byte-deterministic was measured rather than assumed: 300/300 AVRO_EXCEPTION over 40 fresh sync markers plus 260 random and adversarial payloads, never a wrong count.
b Root cause explained? Yes, two halves. AvroRowInputFormat::countRows sums objectCount_ out of each block header and skips the payload (decr plus decoder().drain(), and drain returns unused bytes rather than advancing over a row), while master's pin f2d65e15a324 rejected a negative count only, so a positive count larger than the payload could hold was answered verbatim. The new pin's fit check is then only as strong as the size it is given: uncompressed.size(), materialized and CRC-32 verified, for snappy (DataFile.cc:590); the declared byteCount for null (:539); never called at all for deflate/zstandard (:541-556, :600-616).
c Fix matches root cause? Yes, at both layers. ClickHouse/avro c488095932fb computes minEncodedBytesPerRecord_ in readHeader and calls checkObjectCountFitsPayload in readDataBlock; this PR reverses the two removal hunks, bumps the pin, and gates supportsCountRows() on metadata()["avro.codec"] == "snappy" so the shortcut is taken only where that check runs against a materialized size. No bound widened, no setting re-defaulted, no no-random-* tag, no dataset shrunk, no guard at a crash site. Residual disclosed in the description: on corrupted snappy, the check is skipped when the schema minimum cannot be computed.
d Test intent preserved / new tests added? Yes. All 27 pre-existing .reference cells stay byte-identical and in place (cmp of head -27), so the old test still catches non-termination and invented counts. 04947 now also pins the bound's own diagnostic at both settings, valid counts on all four codecs ClickHouse writes (including 1000 all-NULL rows), a jointly inflated header rejected at both settings, the shortcut answering 5002 from headers alone on an undecodable snappy payload, and the shortcut declined on null/deflate/zstandard, which is the arm that pins the codec gate.
e Both directions demonstrated? Yes, on build-id-verified binaries, one negative control per part of the change: clickhouse-test 04947_... gives E OK (9.40 s, and 50/50 randomized) against A FAIL, B FAIL, C FAIL, D FAIL. B pins the bump (4 cannot fit in cells plus the huge.avro @ ocff=1 flip, the old pin answering 1000005000); D pins the source hunks (no shortcut, so the 5002 cell raises EOF reached); C pins the codec gate (gate dropped, everything else kept: badpayload.avro, huge-deflate.avro and huge-zstd.avro each flip 1 -> 0 at optimize_count_from_files = 1, and nothing else moves).
f Fix is general across code paths? Yes. The gate sits in supportsCountRows(), the single decision point (one caller, IRowInputFormat.cpp:93, after readPrefix()), so no sibling entry into countRows can bypass it; it is deliberately not countRows returning 0, which IRowInputFormat::read() treats as end of input (:96-100), making count() answer 0 silently. The library's negative-header checks are unconditional in readDataBlock, so declining cannot weaken them. AvroForIcebergDeserializer shares the same DataFileReaderBase: an IcebergLocal probe (8 null-codec manifest files, so the bound is applied) gave byte-identical per-file counts, count(), sum() and partition-pruned counts on A and C. AvroConfluentRowInputFormat has no override. ProtobufList/MsgPack were fixed in #115884; Npy is reported in the description, not touched here.
g Fix generalizes across inputs? Yes; the codec is the axis this change turns on, so all four are covered valid and corrupt at both settings: snappy keeps the shortcut, null/deflate/zstandard decline it. Schema matrix {long, string} (min = 2 bytes/record) and a bare null field (min = 0, which disables the bound, the false-reject guard); declared counts -5, -1, 10^9; declared payload -1, 0, 8, 2*10^9 bytes; 1000 valid rows in 139 bytes and 200000 in 810 bytes; max_block_size 1 / 13 / 65505. A missing avro.codec key is the null codec by the library's own readHeader, so declining it is correct rather than a fallback, and the !file_reader_ptr guard covers a future caller before readPrefix.
h Backward compatible? Yes, nothing owed. No setting added, removed or re-defaulted, so no SettingsChangesHistory.cpp entry; no format version, no on-disk format, no protocol. count() on non-snappy Avro now does exactly what master does, so no query that previously succeeded can start failing, and optimize_count_from_files = 0 remains the opt-out. The contrib bump is a fast-forward to a direct child of the current pin and deliberately excludes avro#35's writer changes; files written by A and E read identically on both arms.
i Invariants and contracts preserved? Yes. supportsCountRows() is const, reads only metadata(), which readHeader() populates from the DataFileReaderBase constructor and nothing later mutates, takes no lock and cannot throw, and returning false is always safe, being the state master ships; countRows' contract with IRowInputFormat::read (return 0 only at end of input) is unchanged. The library's throw precedes dataDecoder_->init, so no partially initialized block is left behind, and the bound is a division that a huge objectCount_ cannot overflow, with every undeterminable case returning 0 and disabling it: it can only fail to reject, never falsely reject. Read-only path: no lock, no concurrency contract, no durability obligation.

@clickhouse-gh clickhouse-gh Bot closed this Sep 20, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1d90d40]

Summary: ✅


AI Review

Summary

This PR restores the Avro count() fast path only where the bundled ClickHouse/avro reader now proves the declared block count is bounded by real payload (snappy plus a positive schema-derived lower bound), and it adds focused stateless coverage for both the restored shortcut and the malformed-header regressions. I re-read the current diff, the updated ClickHouse/avro range, the existing review threads, and the current tree’s Iceberg regression coverage; at this point I do not see any remaining correctness, safety, or metadata blockers.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 1d90d40.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 92.10% +0.30%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 9/9 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements submodule changed At least one submodule changed in this PR. labels Sep 20, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). label Sep 20, 2026
Comment thread contrib/avro Resolved
@PedroTadim PedroTadim self-assigned this Sep 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1d90d40a6 with master bfdcb6d6c (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

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

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

Job report

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

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

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
  • StressHouse run: 952fafe2-9f4d-4b65-a2dc-0b18e6cebe96
  • MIRAI run: 93dd166d-4693-42c9-9531-f942845cb5a3
  • PR check IDs:
    • clickbench_3242824_1791149686
    • clickbench_3242837_1791149686
    • clickbench_3242843_1791149686
    • tpch_adapted_1_official_3242854_1791149686
    • tpch_adapted_1_official_3242880_1791149686
    • tpch_adapted_1_official_3242894_1791149686

# 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

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 can you trim this test file?

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 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 counted arm. 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 counted folded into the shortcut is declined where the declared payload size is not verified: same exception at both settings, and inflated-both is 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";

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 why the shortcut only works for the snappy codec?

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.

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, the len < 4 check 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 declared byteCount, 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 decoding filtering_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.

PedroTadim added a commit to ClickHouse/avro that referenced this pull request Sep 21, 2026
… 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]>
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai also bump the avro submodule here. Is the issue not fixed yet?

PedroTadim and others added 2 commits October 3, 2026 09:09
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]>
@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

Bumped contrib/avro to avro master a56fc2f95d18 in c0cbf61.

Yes, it is fixed now. Both defects the description listed were in minEncodedBytes, and ClickHouse/avro#36 closes them. Measured with builds of this head and of the previous pin d90416a:

file previous pin this head
65- and 80-level snappy schema, block declaring 10^9 objects in 8 bytes, optimize_count_from_files = 1 counts 1000000010 rejected at the block header, with both settings
40 levels of a record that inlines and names the next one, explicit structure did not finish in 90 s header read in 0.28 s
recursive A {f0: ["null","A"], f1: ["null","A"]} did not finish in 90 s rejected as recursive in 0.23 s

I also made supportsCountRows return checksDeclaredObjectCount() instead of comparing the codec name, added the 65-level case to 04947, and removed "Not ready to merge" from the description.

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]>
Comment thread contrib/avro Resolved
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]>
@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b90ed3d

Every failure below has an owner: a fixing PR (mine 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
Build (amd_fuzzers) / Build ClickHouse not from this PR: the same job is red on 4 master commits today (87 PRs in 24h); the clickhouse_fuzzer link outgrows the 2 GiB reach of the small code model #122521 (mine, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05237_with_expression_alias_scope_descendant deterministic under a Replicated database: the replicated CREATE VIEW stores a nested WITH alias qualified with the database, so the view reads the same-named table; 95 PRs in 24h a fix task is created (fix in progress, fixing-PR link to follow here)
Mergeable Check, PR rollups, red only because of the rows above #122521 and the fix task above (a fix task is created)

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 FAIL or ERROR on this head.

Session id: cron:our-pr-ci-monitor:20261003-173335

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 05237_with_expression_alias_scope_descendant (DBReplicated): #123774

@PedroTadim
PedroTadim added this pull request to the merge queue Oct 5, 2026
Merged via the queue into ClickHouse:master with commit f2d4521 Oct 5, 2026
149 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 5, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 5, 2026
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]>
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @PedroTadim — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

hellobertrand pushed a commit to hellobertrand/ClickHouse that referenced this pull request Oct 6, 2026
…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]>
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-performance Pull request with some performance improvements 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