Skip to content

Fix aggregation hash table stats cache key for table functions - #109847

Merged
alexey-milovidov merged 16 commits into
ClickHouse:masterfrom
azat:fix-hash-table-stats-cache-key-table-functions
Jul 22, 2026
Merged

alexey-milovidov merged 16 commits into
ClickHouse:masterfrom
azat:fix-hash-table-stats-cache-key-table-functions

Conversation

@azat

@azat azat commented Jul 8, 2026 •

Copy link
Copy Markdown
Member

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):

Fix wrong results for table-function reads with FINAL / SAMPLE under serialize_query_plan = 1, and fix the aggregation hash-table stats cache key for table functions (previously all table functions shared one preallocation entry).

This should fix flakiness of 01730_distributed_group_by_no_merge_order_by_long (#109456)

Closes: #109456

azat and others added 3 commits July 8, 2026 23:43
setAggregationHashTableCacheKeys stamps a plan-derived key over it
during plan optimization anyway. The AST-based key survived only when
plan hashing throws (e.g. in-order aggregation) - a case where the
analyzer keeps key == 0 and skips preallocation; do the same.

Co-Authored-By: Claude Fable 5 <[email protected]>
The key hashed a source step as serialization name + StorageID +
PREWHERE, but a storage created by a table function has no UUID and its
StorageID does not depend on the arguments: after GROUP BY over
numbers(1e6), GROUP BY over numbers(100) preallocated a hash table for
a million keys. Hash the table-expression subtree (function name and
resolved arguments) for table functions; this also covers s3, url,
generateRandom, etc.

Co-Authored-By: Claude Fable 5 <[email protected]>
@azat
azat requested review from nickitat and novikd July 8, 2026 21:56
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a81e9b3]

Summary: ✅


AI Review

Summary

This PR correctly restores FINAL / SAMPLE for ordinary table-function reads on the serialized-plan path and fixes the simple TableFunctionNode hash-table-stats collision, but it still misses the parameterized-view carrier that the analyzer models as a TableNode. That leaves one remaining serialized-plan correctness bug and one remaining stats-key collision, so I cannot approve it yet.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/resolveStorages.cpp:175-226] Parameterized views still lose their substituted arguments across serialize_query_plan. QueryAnalyzer::resolveTableFunction rewrites pv(x = 1) into a synthetic TableNode with the original StorageID, and this function only preserves extra identity for real TableFunctionNodes. When the logical plan ships ReadFromTableStep("db.pv"), the worker resolves the catalog view by name and no longer has the substituted inner query, so shard-side execution can run the unspecialized view body or fail with UNKNOWN_QUERY_PARAMETER.
    Suggested fix: serialize parameterized-view reads with the original table-function subtree or the substituted inner query, and reconstruct that on the worker instead of resolving only by StorageID.

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/calculateHashTableCacheKeys.cpp:47-54] The aggregation hash-table-stats key is still incomplete for parameterized views. The analyzer rewrites pv(x = ...) into a TableNode, and TableNode::updateTreeHashImpl already mixes in the substituted inner query specifically so different parameter values stay distinct, but this pass hashes only TableFunctionNodes. pv(x = 1) and pv(x = 1000000) therefore still reuse one preallocation entry.
    Suggested fix: hash the full table_expression identity here (or at least the parameterized-view TableNode case), not just TableFunctionNode.
Tests
  • ⚠️ Add a serialized-plan regression for a parameterized view call that proves the substituted parameter values survive the ReadFromTableStep / resolveStorages round-trip on a worker.
  • ⚠️ Add a focused aggregation-stats regression for parameterized views showing that two different parameter sets do not share one hash-table preallocation entry.
Final Verdict
  • Status: ❌ Block

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jul 8, 2026
/// numbers(1e6) would share a stats entry.
if (const auto & table_expression = read.getQueryInfo().table_expression)
{
if (table_expression->as<TableFunctionNode>())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

TableFunctionNode is not the only supported table-function shape here. QueryAnalyzer::resolveTableFunction rewrites parameterized views like my_view(x = 1) into a synthetic TableNode, and buildParameterizedViewStorage gives every instantiation the same StorageID(database, table). After that rewrite this branch is skipped, so different parameter values still fall back to storage_id.getFullTableName() and reuse each other's aggregation stats.

Please preserve and hash the original call arguments for that case as well, for example by carrying the original table-function subtree (or its resolved hash) through SelectQueryInfo.

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.

Good catch, and this one is a genuine gap (in analyzer mode too), not just the legacy path: QueryAnalyzer::resolveTableFunction rewrites view(x = ...) into a synthetic TableNode, buildParameterizedViewStorage reuses one StorageID(database, table) for every parameter set, and this branch only matches TableFunctionNode, so different parameters collapse to the same key.

Handling it properly means preserving the original table-function subtree (or a hash of its resolved arguments) across that rewrite and carrying it on SelectQueryInfo, then hashing it here even when the node has become a TableNode — an analyzer change on top of the plan-hash infrastructure rather than something local to this optimization. Since it is a separate correctness gap from the 01730_... flakiness this PR targets, I'd prefer to do it as a follow-up and would defer the scope/approach to @novikd. Flagging it here so it is not lost.

alexey-milovidov and others added 2 commits July 14, 2026 16:54
…lized-plan path

`calculateHashFromStep` mixes the table function subtree into the aggregation
hash-table-stats cache key, but that subtree is only available when
`SelectQueryInfo.table_expression` is populated. `PlannerJoinTree` sets it on the
analyzer read path, but the `resolveStorages` reconstruction of a deserialized
`ReadFromTableFunctionStep` (distributed / `serialize_query_plan`) did not, so the
key hashed only the storage name (`_table_function.numbers` for any `numbers(N)`)
and different arguments shared one stats entry on the shard side.

Set `select_query_info.table_expression` to the resolved `TableFunctionNode` in
`resolveStorages` before `storage->read`, mirroring the analyzer path. The only
local consumers of `table_expression` check for `TableNode`, so a `TableFunctionNode`
is a no-op for them; the value is a preallocation hint and never affects results.

Extend `04509_hash_table_sizes_stats_table_functions` with a
`cluster('test_shard_localhost', numbers(...))` case under `serialize_query_plan=1`
that reads the shard-side (secondary) aggregation preallocation, so `numbers(1e6)`
and `numbers(800e3)` are shown to preallocate 1000000 and 800000 distinctly.

Verified locally: with the fix the secondary aggregations preallocate 1000000 and
800000; the extended test passes across repeated runs.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…an path

ReadFromTableStep and ReadFromTableFunctionStep serialize FINAL / SAMPLE
out-of-band from the table name / table function AST, and resolveStorages
never put them back:

- On the direct-read path, the TableFunctionNode reconstructed from
  serialized_ast carried no modifiers, so the hash-table-stats key could
  not tell modifier-bearing reads apart.
- For remote / Merge storages, the query AST constructed for
  InterpreterSelectQueryAnalyzer dropped the modifiers entirely, so e.g.
  SELECT ... FROM cluster(..., merge(...)) FINAL read non-collapsed data
  under serialize_query_plan (verified: the FINAL query returned 1e6
  groups instead of 600e3 before this fix), and both reads shared one
  aggregation-stats entry.

Copy the modifiers onto the reconstructed TableFunctionNode and restore
them on the constructed ASTTableExpression. Extend the test with a
ReplacingMergeTree read through merge() with and without FINAL; the
FINAL group count is kept above the 500e3 lower bound below which
getSizeHint skips preallocation.
@alexey-milovidov

Copy link
Copy Markdown
Member

The Integration tests (amd_tsan, 3/6) failure is test_replicated_database/test.py::test_replicated_table_structure_alter — the known flaky test #110036, unrelated to this PR (the change only affects aggregation hash-table-stats cache keys on the serialized-plan path). A fix is in progress in #110145. The new push re-runs the shard in any case.

@alexey-milovidov

Copy link
Copy Markdown
Member

The new test is too long for the flaky check.

In the flaky check 04509_hash_table_sizes_stats_table_functions averaged
~75 seconds per run on amd_debug/amd_asan_ubsan (with a few runs above the
180 seconds limit), and its 50 sequential reruns chained to about an hour
of that job.

Shrink the aggregated group counts from 1e6/800e3 to 650e3/520e3 - they
must stay above the 500e3 lower bound under which `getSizeHint` does not
preallocate at all with a single hash table (and `max_threads = 1` is
required for the exact reference values) - and move the FINAL table
expression modifiers case (which additionally inserts and reads a
two-part ReplacingMergeTree table) into a separate test
04613_hash_table_sizes_stats_table_expression_modifiers, so the flaky
check reruns of the two halves proceed in parallel workers instead of one
long sequential chain.

Verified against a local server with process_query_plan_packet enabled:
both tests plus 04612 pass 5/5 on a binary with the fix, and all three
fail with the expected collision / dropped-modifier signatures on a
master binary without it.

ClickHouse#109847 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Addressed #109847 (comment) in a938035: in the flaky check 04509_hash_table_sizes_stats_table_functions averaged ~75 s per run on amd_debug/amd_asan_ubsan (a few runs exceeded the 180 s limit), and its 50 sequential reruns chained to about an hour of that job.

Two changes:

  • Shrunk the aggregated group counts from 1e6/800e3 to 650e3/520e3. They cannot go lower: getSizeHint does not preallocate at all when sum_of_sizes ≤ 500e3 with a single hash table, and max_threads = 1 is required for exact reference values (with several threads the preallocated amount is median_size per thread, which depends on the racy per-thread split).
  • Moved the FINAL modifiers case (the heaviest section: it inserts and reads a two-part ReplacingMergeTree table) into a separate test 04613_hash_table_sizes_stats_table_expression_modifiers, so the flaky-check reruns of the two halves run in parallel workers instead of one long sequential chain.

Verified locally against a server with process_query_plan_packet enabled: both tests plus 04612 pass 5/5 on a binary with the fix, and all three fail with the expected collision / dropped-modifier signatures on a master binary without it (so the smaller sizes still catch the bug). Note: the commit message links a wrong comment id; the correct one is above.

The new test `04613_hash_table_sizes_stats_table_expression_modifiers`
read `system.query_log` without a `current_database = currentDatabase()`
condition, which the `various_checks.sh` style check requires in any test
that queries `system.query_log`/`system.query_thread_log`. The Style check
failure fail-fast-aborted the whole workflow, which is why every downstream
job (builds, Bugfix validation) showed up as DROPPED and the
`new_tests_check` post-hook then reported "No per-arch Bugfix Validation
job validated the bug".

The preallocation counters are read from the secondary (`is_initial_query = 0`)
rows, and secondary queries on the executor run as the `default` user, so
their `current_database` is `default` rather than the test database - filtering
those rows directly by `current_database = currentDatabase()` would drop them
all and break the test (the same reason 04509 does not filter its secondary
block that way). Instead scope the secondary rows to this test via their
initiator, which does run in `currentDatabase()`, mirroring the pattern in
`04029_distributed_index_analysis_sampling` and
`04201_max_bytes_ratio_before_external_join_distributed`. This both satisfies
the style check and tightens the test's isolation from other tests' query_log.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Pushed 79c0e06216c to fix the two CI reds on a9380357, both of which stemmed from a single style-check violation:

  • Style check: the new test 04613_hash_table_sizes_stats_table_expression_modifiers.sh read system.query_log without a current_database = currentDatabase() condition, which various_checks.sh requires.
  • Finish Workflow (new_tests_check): the style failure fail-fast-aborted the whole workflow, so every downstream job (all builds and the per-arch Bugfix validation) showed up as DROPPED with 0s, and the post-hook then reported "No per-arch Bugfix Validation job validated the bug".

The preallocation counters are read from the secondary (is_initial_query = 0) rows, and secondary queries on the executor run as the default user, so their current_database is default, not the test database — filtering those rows directly by current_database = currentDatabase() would drop them all (the same reason 04509 does not filter its secondary block that way). Instead the secondary rows are now scoped to this test via their initiator, which does run in currentDatabase(), mirroring 04029_distributed_index_analysis_sampling and 04201_max_bytes_ratio_before_external_join_distributed. This satisfies the style check and tightens the test's isolation.

Verified locally against a binary without the fix: the reworked query_log read still returns both secondary rows and yields final-prealloc 650000 (the dropped-FINAL bug signature vs. the reference 520000), confirming the row-matching logic is correct and the test still detects the bug on master HEAD (so per-arch Bugfix validation will validate it once the workflow re-runs).

alexey-milovidov and others added 2 commits July 21, 2026 23:56
Merging `master` (1512 commits) brought in new stateless tests at numbers
`04612` and `04613`, which collided with this PR's
`04612_serialize_query_plan_table_function_sample` and
`04613_hash_table_sizes_stats_table_expression_modifiers`. Renumber the two
tests added by this PR to `04624` and `04625` (updating their internal table
names and query-id prefixes accordingly) to keep test numbers unique.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged master (1512 commits) into the branch, pushed as a81e9b34ff1.

The merge brought in two new stateless tests on master (04612_* and 04613_*) whose numbers collided with the tests added by this PR (04612_serialize_query_plan_table_function_sample and 04613_hash_table_sizes_stats_table_expression_modifiers). I renumbered this PR's two tests to 04624 and 04625 (updating their internal table names and query-id prefixes) to keep test numbers unique. The four changed translation units (Aggregator.cpp, InterpreterSelectQuery.cpp, resolveStorages.cpp, calculateHashTableCacheKeys.cpp) compile cleanly against the merged tree.

The two CI reds on 79c0e06216c were unrelated flaky failures in the Stateless tests (amd_llvm_coverage, old analyzer, ...) and Integration tests (amd_asan_ubsan, db disk, old analyzer) shards:

  • Server died (532 occurrences on master/other PRs in the last 10 days) plus the 04411_docs_web_ui_source_link_and_categories ERROR (a consequence of that shard's server dying) and the Logical error: Arguments of ... have incorrect data types blocker in FunctionBinaryArithmetic<MultiplyImpl> partial-result evaluation (66 occurrences on master/other PRs) — a fuzzer-induced crash in that coverage shard, not related to this PR's hash-table-stats change.
  • test_check_table/test.py::test_check_all_tables (retry_failed, 52 occurrences on master/other PRs) — known flaky integration test.

Merging master reruns CI on a fresh base to clear these.

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 43/45 (95.56%) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member

Status update on a81e9b34:

  • Public CI: fully green (all builds, functional, integration, Bugfix validation passed).
  • New AI Blocker on resolveStorages.cpp — refuted with empirical evidence and resolved (thread). The claimed parameterized-view argument loss over ReadFromTableStep is not a serialize_query_plan-specific failure: the only shape that puts a parameterized view into a shard-side fragment (local JOIN with a distributed read) fails identically with serialize_query_plan = 0 and = 1 on current master — the arguments are dropped by the initiator's distributed head-query rewrite during analysis, before any plan is serialized. GLOBAL JOIN and regular views in shipped plan fragments work correctly in both modes (verified on a live server with process_query_plan_packet, Received query plan confirmed in the trace log). This PR's hunks are provably inert for a plain view leaf, so the pre-existing gap is unchanged; carrying the substituted inner query across the analyzer rewrite remains the follow-up deferred to @novikd in the standing thread.
  • CH Inc sync was stuck in PENDING: the private sync PR was already at a81e9b34 and MERGEABLE, but the branch update never triggered the private PR workflow. Re-triggered it (close/reopen); private CI is running now and the public status will refresh when it finishes.

No code changes needed this pass. Remaining: the standing parameterized-view cache-key design follow-up (deferred to @novikd) and human merge.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 22, 2026
Merged via the queue into ClickHouse:master with commit 009ea51 Jul 22, 2026
179 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 Jul 22, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
In the flaky check 04509_hash_table_sizes_stats_table_functions averaged
~75 seconds per run on amd_debug/amd_asan_ubsan (with a few runs above the
180 seconds limit), and its 50 sequential reruns chained to about an hour
of that job.

Shrink the aggregated group counts from 1e6/800e3 to 650e3/520e3 - they
must stay above the 500e3 lower bound under which `getSizeHint` does not
preallocate at all with a single hash table (and `max_threads = 1` is
required for the exact reference values) - and move the FINAL table
expression modifiers case (which additionally inserts and reads a
two-part ReplacingMergeTree table) into a separate test
04613_hash_table_sizes_stats_table_expression_modifiers, so the flaky
check reruns of the two halves proceed in parallel workers instead of one
long sequential chain.

Verified against a local server with process_query_plan_packet enabled:
both tests plus 04612 pass 5/5 on a binary with the fix, and all three
fail with the expected collision / dropped-modifier signatures on a
master binary without it.

ClickHouse#109847 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ache-key-table-functions

Fix aggregation hash table stats cache key for table functions
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Sep 13, 2026
… its memory cap off the initiator peak

The test asserts that its distributed_group_by_no_merge=0 query exceeds
max_memory_usage. On master 22fae87 (Stateless tests (amd_tsan, parallel))
the query completed instead, so the negative assertion never fired and the
test failed with "The query succeeded but the server error '241' was
expected".

The peak that assertion targets is correct and structural. With
no_merge=0 each of the 10 shards aggregates its own numbers(1e6)
single-stream, so AggregatingStep zeroes group_by_two_level_threshold and
every block ships with bucket_num = -1. With purely single-level input
GroupingAggregatedTransform cannot push anything until every input port
has finished, so distributed_aggregation_memory_efficient buys nothing
here and the initiator holds all 10 shards' output at once: 76.29 MiB of
buffered blocks (10 x 1e6 x 8 B) plus the merged key64_void table and its
7.63 MiB result.

The defect is that the test picked its cap equal to that peak. In the
failing job's own query_log the initiator peaked at 99.14 MiB against the
100.00 MiB cap, a margin of 903,301 B (0.87%), while the server's
per-thread untracked-memory quantum is 1 MiB. Whether the run crossed
104,857,600 B was therefore decided by allocation noise of the same
magnitude as the margin, which is why 4 of 4 diagnosis reruns passed and
the failure rate is roughly 1 in 180 days.

Lower the cap shared by the two paired queries from 100Mi to 64Mi. The
window is bounded above by the initiator peak (99.14 MiB) and below by
query 1's own per-shard peak (41.00 MiB), which has to stay under the cap
so the 241 is raised on the initiator and not on a shard. Query 2, the
positive half of the pair, floors lower still at 30.22 MiB, so it keeps
2.12x headroom. 100Mi sat above the top of that window; 64Mi is its
geometric middle, sqrt(41.00 x 99.14) = 63.76, so the binding margin
grows from 0.87% to about 55% on both sides. Both queries keep the same
cap, so the pair remains an honest A/B in which only
distributed_group_by_no_merge differs, and the negative assertion becomes
strictly harder to satisfy rather than easier.

Queries 3 and 4 keep their own caps deliberately. Query 4's measured peak
is 54.03 to 56.30 MiB, so at 64Mi its headroom would fall to about 1.18x
and it would become the next flake.

This test has one other live failure mode, which this change neither
fixes nor disturbs: query 2's shard sometimes attempts a single 512.00
MiB allocation in AggregatingTransform and blows the cap outright, 256
times in the last 365 days. It stopped on every lane when ClickHouse#109847 merged
on 2026-07-22, except Stateless tests (amd_asan_ubsan, distributed plan,
parallel), where it last fired on 2026-09-03. The size is exactly 512.00
MiB in 256 of 256 samples, with none at 128 or 256 MiB, so it clears the
old and the new cap identically and there is no intermediate regime that
100Mi absorbed and 64Mi would not.

Validated on a debug build with the CI test configs installed: 50/50
runs, 5/5 with enable_analyzer=0 for the old analyzer lanes, and 5/5 with
serialize_query_plan=1, the setting the distributed plan lanes install,
which is also the only arm where query 1 has the initiator serialize the
shard plan. Raising the cap back above the peak reproduces the original
failure message, so the oracle is live rather than merely satisfied.

Co-Authored-By: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants