Skip to content

Regression test for KeyCondition over a LowCardinality key exposed through Merge - #110326

Merged
alexey-milovidov merged 23 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-keycondition-lowcardinality-key-over-merge
Sep 14, 2026
Merged

alexey-milovidov merged 23 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-keycondition-lowcardinality-key-over-merge

Conversation

@groeneai

@groeneai groeneai commented Jul 13, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #109699
Related: #111050
Related: #117054

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Description

A regression test for the LowCardinality handling in KeyCondition's monotonic-function chain execution. This pull request is now test-only.

It started as a bug fix for the AST fuzzer LOGICAL_ERROR "Arguments of minus/plus have incorrect data types" (STID 2735-50e2, AST fuzzer (amd_debug)): KeyCondition::applyFunction executed a monotonic key function on the raw index column while the function was resolved against the plain key type, which happens when a Merge table declares a plain header (e.g. UInt32) over a source whose key column is LowCardinality(UInt32).

The exception is already fixed on master by #111050 (merged 2026-08-05), which normalizes the chain's input type inside applyMonotonicFunctionsChainToRange and declares the appended supertype cast against the chain's own result type. #117054 (merged 2026-09-12) then reworked the sparse checkInHyperrectangle site so that it always goes through that helper. The test added here passes in full against master's KeyCondition.cpp, and instrumenting every branch this pull request used to add to KeyCondition.cpp showed that none of them changed the outcome of any statement in the test. Those production hunks were therefore dropped when resolving the merge conflict with #117054, as the review asked; the changelog category is Not for changelog, and Closes: #109699 was downgraded to Related: because that fuzzer issue is closed by #111050.

What lands:

  • tests/queries/0_stateless/05136_key_condition_lowcardinality_key_over_merge.sql — regression coverage for the shapes Fix Bad cast in KeyCondition for nested CAST that re-introduces LowCardinality #111050 fixed: the dense cached-column path, the sparse constant-coordinate (partition-minmax) path, the explicit-field path in both LowCardinality directions, and two-link cast chains whose intermediate result type re-introduces LowCardinality. Each case pairs its count with an EXPLAIN indexes = 1 granule-pruning oracle and a full-scan control, so a silently declined chain cannot pass the test.

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

Version info

  • Merged into: 26.9.1.1482 (included in 26.9 and later)

…ough Merge

KeyCondition::applyFunction executed a monotonic key function on the raw
index column while the function was resolved against the plain key type.
When a Merge table declares a plain header (e.g. UInt32) over a source
whose key column is LowCardinality(UInt32), the index column loaded from
the child part is LowCardinality but the function expects the plain type,
so the function received a LowCardinality column dispatched as its plain
type and threw a LOGICAL_ERROR ("Arguments of 'minus' have incorrect data
types") during primary-key index analysis - a server abort in debug and
sanitizer builds.

Strip LowCardinality from the argument column and its type in lockstep
before executing, mirroring the sibling applyFunctionChainToColumn which
already does convertToFullColumnIfLowCardinality + removeLowCardinality.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SET allow_suspicious_low_cardinality_types=1; CREATE TABLE s (k LowCardinality(UInt32)) ENGINE=MergeTree ORDER BY k; INSERT INTO s SELECT number FROM numbers(100000); CREATE TABLE m (k UInt32) ENGINE=Merge(currentDatabase(),'s'); SELECT count() FROM m WHERE 3 = (65536 - k); aborts every time on master HEAD.
b Root cause explained? KeyCondition::applyFunction executes a monotonic key function (minus/plus) on the raw index column while the function is resolved against the plain key type. A Merge table with a plain header (UInt32) over a LowCardinality(UInt32) source loads a LowCardinality index column, so the plain-typed function receives an LC column dispatched as its plain type and throws the LOGICAL_ERROR during PK index analysis. Both reported arg types are UInt32 because the divergence is column-representation vs declared-type.
c Fix matches root cause? Yes. It strips LowCardinality from the argument column and its type in lockstep before executing, exactly addressing the column-vs-type divergence.
d Test intent preserved / new tests added? New regression test 04350_key_condition_lowcardinality_key_over_merge added (minus, plus, FINAL, and a PK-pruning correctness check).
e Both directions demonstrated? Yes. Master HEAD (Build ID AC3F3907): test fails with server died and the exact fuzzer error. With the fix (Build ID 7C2A6E88): test passes.
f Fix is general across code paths? Yes. The sibling monotonic-chain path applyFunctionChainToColumn already strips LC the same way; this makes the two consistent. The non-PK / regular filter path already unwraps LC via the function LC adaptor (verified: minus over a non-PK column does not abort).
g Fix generalizes across inputs? Verified with plain UInt32, LowCardinality(UInt32), and LowCardinality(Nullable(UInt32)) PK columns, for both minus and plus, with and without FINAL. recursiveRemoveLowCardinality-equivalent stripping recurses through wrappers. PK-pruning result over the LC key equals the plain-key result (5001 == 5001), so the optimization is preserved, not just correctness.
h Backward compatible? Yes. No setting default, on-disk/wire format, or validation change. Pure execution-path fix; behavior for non-LC keys is unchanged.
i Invariants and contracts preserved? Yes. func->execute requires argument columns whose representation matches the declared arg type; the fix restores that contract by delivering a full (non-LC) column with a plain type. The result column and downstream FieldRef monotonic-range logic are unchanged; the sibling path already relied on the same stripping.

Session id: cron:clickhouse-worker-slot-0:20260713-222100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @KochetovNicolai — could you review this? It fixes a LOGICAL_ERROR during primary-key index analysis: KeyCondition::applyFunction ran a monotonic key function on a LowCardinality index column while the function was resolved against the plain key type, which happens for a Merge table with a plain header over a LowCardinality-key source. The fix strips LowCardinality from the argument column and type before executing, mirroring the existing applyFunctionChainToColumn.

@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cc7850f]

Summary: ✅


AI Review

Summary

This PR is now a test-only addition for the KeyCondition/LowCardinality over Merge regression paths that are already fixed on master. I reviewed the current SQL and reference files against the final diff and the full prior discussion, including the previously open cache-control thread, and I did not find any new correctness, coverage, or PR-metadata issues in the current revision.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 14, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
…e caller

The sparse primary-key analysis path forwarded the raw key type
(sparse_data_types[sparse_pos]) into applyMonotonicFunctionsChainToRange,
while the monotonic function chain is built in extractAtomFromTree against a
LowCardinality-stripped key type. When a key column is analysed as a
partition-minmax constant coordinate over a LowCardinality source (e.g. a
Merge table whose header declares the plain type), the explicit-field
applyFunctionForField built a LowCardinality const column against a chain
prepared on the plain type. With a CAST wrapper the dictionary-unpack step is
elided and the inner cast wrapper rejects the LowCardinality column with a Bad
cast LOGICAL_ERROR (server abort in debug/sanitizer builds).

Strip LowCardinality here too, mirroring the dense checkInHyperrectangle
caller. Regression test extended with the sparse constant-coordinate path.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
…tion site

extractAtomFromTree builds the monotonic function chain against
recursiveRemoveLowCardinality(key_column_type), but the applyFunction cache-miss
branch stripped only a top-level LowCardinality wrapper. A Merge table with a
plain Array(T) header over a child Array(LowCardinality(T)) then leaves the
argument type plain while the column is a ColumnArray whose nested data is
ColumnLowCardinality, diverging from the type the chain was built on. Use
recursiveRemoveLowCardinality for both the column and its type so nested
LowCardinality is unwrapped in lockstep. Extend the Merge regression with an
Array(LowCardinality(T)) key exposed through a plain Array(T) header.
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
…field path

The monotonic function chain loop in applyMonotonicFunctionsChainToRange
propagates current_type = result_type, so an intermediate function that
returns LowCardinality (e.g. toLowCardinality) reverts the running type to
LowCardinality even though the caller passed the recursively-stripped key
type. On the partition-minmax constant-coordinate (explicit field) path this
reached applyFunctionForField with a LowCardinality arg_type, building a
LowCardinality const column that the next function (a Bool CAST wrapper)
rejected with a Bad cast (ColumnLowCardinality to ColumnVector<char8_t>)
LOGICAL_ERROR during PK/partition index analysis (server abort in
debug/sanitizer builds). Strip LowCardinality recursively in
applyFunctionForField, mirroring the cached branch of applyFunction.

Found by AST fuzzer (STID 1499-6033) on this PR's own regression test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 5de1d6c

CI is fully finished on this head (Finish Workflow + Mergeable Check + PR all green). Every failure has an owner.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / STID 1499-6033 Bad cast ColumnLowCardinality -> ColumnVector<char8_t> (on prior head 6f59243) PR-caused (fuzz mutation of this PR's own 04350 test; mid-chain-LC explicit-field path) PR-caused, fixed in this PR @ 5de1d6c (applyFunctionForField now strips LowCardinality; regression added). 0 failures on current head.
Report messages 10 warning(s), informational meta-check (non-blocking) N/A (not a test failure)
CH Inc sync private sync CH Inc sync (private, not actionable by us)

Session id: cron:our-pr-ci-monitor:20260714-110000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 5de1d6c

CI is fully finished and clean. No test failures.

Check / test Reason Owner / fixing PR
(none) all checks passed —
CH Inc sync — CH Inc sync (private, not actionable by us)

Session id: cron:our-pr-ci-monitor:20260715-053000

…ey-over-merge

Reconcile the KeyCondition::applyFunction cache-miss LowCardinality strip
with the sibling fix from ClickHouse#110006 (merged): keep the recursive strip
(covers nested Array(LowCardinality(T))) for the input column and type,
and keep ClickHouse#110006's result hardening (removeLowCardinality on the result
type + convertToFullColumnIfLowCardinality on the result column).
applyFunctionForField and the sparse checkInHyperrectangle caller retain
their recursive strips.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 929e3be (merge-resolution head)

CI is complete on this head (Finish Workflow + Config Workflow pass; Mergeable/PR reflect the one failure below). This ledger covers the new head after the master merge-conflict resolution; the prior ledger (issuecomment-4968486612) covered 5de1d6c. Every failure has an owner.

Check / test Reason Owner
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 04507_mvt_encode_state_serialize flaky trunk bug (MVTEncodeMerge state-serialize Code 70 Cannot convert Tuple to Geometry; unrelated to this PR's KeyCondition/LowCardinality diff) a fix task is moved to pending (investigating at full effort; fixing-PR link to follow here)
CH Inc sync — CH Inc sync (private, not actionable)

04507_mvt_encode_state_serialize is a trunk failure spiking today: CIDB shows it hitting master (4x) plus 15 distinct unrelated PRs, all within 2026-07-20 13:19-16:30 UTC. This PR's diff touches only KeyCondition.cpp and the 04350 regression test (LowCardinality key through Merge), which is structurally unrelated to MVT geometry-aggregate serialization. Not PR-caused.

Session id: cron:our-pr-ci-monitor:20260720-180000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the 04507_mvt_encode_state_serialize finish-ledger line (Code 70 Cannot convert type Tuple(Float64, Float64) to Geometry under ParallelReplicas): #111136. That is a trunk bug in the query-tree to AST conversion of folded Variant constants, unrelated to this PR's diff.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 71c512b

Every failure below has an owner: a fixing PR, or a full-effort fix task whose
fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky on this lane: secondary replicas are built without setQueryId, so the per-table max_concurrent_queries throttle sees several random query ids for one statement and the query competes against itself #112385 (ours, open)

Session id: cron:our-pr-ci-monitor:20260729-083000

A monotonic key function is resolved against the previous chain link's result
type, while applyMonotonicFunctionsChainToRange propagates
current_type = result_type and the caller passes a recursively-stripped key
type. The running type and the type a link was built against can therefore
disagree over LowCardinality in either direction. FunctionCast keeps
useDefaultImplementationForLowCardinalityColumns = false and its wrapper casts
the column to the declared argument type, so either disagreement is a bad cast
and throws a LOGICAL_ERROR exception, which terminates debug and sanitizer
builds.

Align both execution sites with the declared argument type, guarded by equality
once LowCardinality is removed so only LowCardinality-ness is ever adjusted and
never the value type:

  - applyFunctionForField (explicit-field path) builds the const column against
    the declared type.
  - the applyFunction cache-miss branch strips column and type in lockstep and
    then restores the declared representation. Stripping must be recursive: a
    top-level lowCardinality() check misses a nested Array(LowCardinality(T))
    under a plain Array(T) Merge header.

Measured against an ENGINE = Memory twin as the oracle, on a Merge table with a
plain Bool header over a LowCardinality(Bool) key source. A one-directional
strip is not sufficient: CAST(toLowCardinality(b), 'UInt64') > 0 threw
Bad cast ColumnVector<char8_t> -> ColumnLowCardinality, while reverting the
strip instead threw for
toLowCardinality(b) > toNullable(toLowCardinality(false)) in the opposite
direction. Both directions pass after aligning.

The regression test asserts the previously throwing cases and pins pruning for
the dense, sparse and nested-Array carriers.

Closes: ClickHouse#109699.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a9799c4

Every failure below has an owner: a fixing PR (ours 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
Fast test / 04350_key_condition_lowcardinality_key_over_merge PR-caused — this PR's own new test. Reason: having stderror, from the Table can't create parts with adaptive granularity, but settings min_rows_for_wide_part = 0, min_bytes_for_wide_part = 10485760 warning the test's own CREATE TABLE emits on both t_04350_lc and t_04350_plain. Fast test treats a non-empty stderr as failure PR-caused → fixed in this PR
Finish Workflow / Post Hooks — "No per-arch Bugfix Validation job validated the bug" consequence of the row above — Fast test failing dropped Build (amd_binary) / Build (arm_binary), so all four per-arch Bugfix Validation jobs report DROPPED/SKIPPED and the gate has nothing to read. It will clear once Fast test is green PR-caused → fixed in this PR

Session id: cron:our-pr-ci-monitor:20260729-103000

The three CREATE TABLE statements that pin index_granularity_bytes = 0 kept the
default min_bytes_for_wide_part = 10485760, so MergeTreeData logged a warning at
CREATE time for each of them:

  Table can't create parts with adaptive granularity, but settings
  min_rows_for_wide_part = 0, min_bytes_for_wide_part = 10485760. ...
  will be ignored.

clickhouse-test runs with send_logs_level=warning and fails any test whose
stderr is non-empty, so the warning alone reddened Fast test with
"Reason: having stderror" while stdout already matched the reference exactly.
Fast test does not install tests/config/config.d/polymorphic_parts.xml (that
symlink is gated on USE_POLYMORPHIC_PARTS), which is why the setting keeps its
non-zero default there.

Setting min_bytes_for_wide_part = 0 on those three tables cannot change the part
layout: with adaptive granularity off, MergeTreeData::choosePartFormat returns
Wide/Full before it reads either wide-part threshold, which is exactly what the
warning means by "will be ignored". Verified locally that the part type, part
count and mark count are unchanged, that stderr goes from 471 bytes to 0, and
that the test's stdout is byte-identical to the reference.
@groeneai

groeneai commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e1e384b

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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky under parallel replicas #112385 (mine, merged 2026-07-29 15:37 UTC). Not yet an ancestor of this head, so this build predates the fix.
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Logical error: Got read request from replica N for unknown stream ... (STID 5217-5b3d) + Server died trunk bug, parallel replicas with projection short-circuit #111689 (mine, open)
Integration tests (amd_tsan, 4/6) / test_refreshable_mv_no_multi_read.py::test_refreshable_mv_unavailable_view_refuses_replicated_start the integration suite's own Keeper configs clamp the session timeout to 10 s (session_timeout_ms=10000 is read as the server MAX cap while min_session_timeout also defaults to 10000, so the clamp is unconditional), so a TSAN stall longer than 10 s kills the session and the in-flight DDL surfaces Connection loss (Code 999) a fix task owns this and is already implementing a fix (fixing-PR link to follow here)
Sync - CH Inc sync (private, not actionable)

STID 5217-5b3d over 30 days: 118 hits across 104 distinct PRs including 9 on master, so it is
not caused by this PR (which changes KeyCondition only).

Session id: cron:our-pr-ci-monitor:20260729-203000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Following up on the CI finish ledger: the fixing PR for the
Integration tests (amd_tsan, 4/6) /
test_refreshable_mv_unavailable_view_refuses_replicated_start failure is now open as
#112508.

Root cause is not in this PR's diff. That suite set its embedded Keeper's maximum session
timeout to the same value as the default minimum, so every session was clamped to 10 s and a
quiet period past that killed the session under whatever Keeper call was in flight. The stack
frame varies per carrier because the session dies underneath whichever Keeper call is in flight,
so the frame is not the cause.

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

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

Full report · Diff report

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9864ff3

Every failure below has an owner: a fixing PR (ours 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
Stress test (arm_msan) / Query context must be created after authentication (STID 3197-391f) trunk bug: pre-auth query context on the PostgreSQL wire port, not reachable from this diff a fix task is moved to pending (investigating at full effort, fixing-PR link to follow here)
Stress test (arm_asan_ubsan) / Query context must be created after authentication (STID 3197-391f) same trunk bug, second build flavour a fix task is moved to pending (investigating at full effort, fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20260801-230000

@alexey-milovidov alexey-milovidov added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 12, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 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: 074772b8-099b-4d82-81d0-dc38ef8b5b17
  • MIRAI run: 4c7e223b-780c-472a-a4ba-c69a48ba2b88
  • PR check IDs:
    • clickbench_260210_1789263698
    • clickbench_260216_1789263698
    • clickbench_260222_1789263698
    • tpch_adapted_1_official_260233_1789263698
    • tpch_adapted_1_official_260244_1789263698
    • tpch_adapted_1_official_260281_1789263698

alexey-milovidov and others added 2 commits September 13, 2026 11:48
…dition-lowcardinality-key-over-merge

Resolved the conflict in `src/Storages/MergeTree/KeyCondition.cpp` by taking
`master`'s version wholesale, which makes this pull request test-only.

`master` already normalizes the chain's input type inside
`applyMonotonicFunctionsChainToRange` (ClickHouse#111050), and ClickHouse#117054 reworked the sparse
`checkInHyperrectangle` site that this branch had edited so that it always goes
through that helper. Every branch this pull request added to `KeyCondition.cpp`
was measured on the previous merge base to change no statement outcome of the
regression test, and the review thread asked to either drop the hunks or guard
them; dropping them is the accurate resolution.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The pull request is test-only now, so the comment must not speak of "this fix".

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

Copy link
Copy Markdown
Member

🕵 Merged master (846 commits behind) and pushed 1cd2dea20c57. The branch was CONFLICTING because #117054 (merged 2026-09-12) reworked the sparse checkInHyperrectangle site this branch had edited. Since every KeyCondition.cpp branch here was already measured to change nothing on top of #111050, and the review asked to drop or guard them, I resolved the conflict by taking master's KeyCondition.cpp wholesale: this pull request is now test-only (05136_key_condition_lowcardinality_key_over_merge.sql + reference, 228 added lines, nothing else). Description updated accordingly, and the open review thread is resolved.

Verified locally on the merged tree: clickhouse builds clean and the test passes in four runs, one pinned and three with randomized settings. The CH Inc sync red belonged to the previous head and re-runs on this push.

@clickhouse-gh clickhouse-gh Bot added comp-testing Test content only (no production code). and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Sep 13, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pass 2026-09-13 (head 1cd2dea20c57): all public checks are green, the AI review approves, and there are no unresolved threads. The branch merges cleanly with master (223 commits behind, test-only diff), so nothing was pushed.

The only red is CH Inc sync ("tests failed (1 new, 1 known)") on https://github.com/ClickHouse/clickhouse-private/pull/64365: 04238_alter_rename_column_merge_race (known, https://github.com/ClickHouse/clickhouse-private/issues/63795) and 04321_table_readonly_background_merges (a TTL-timing flake under the slow amd_debug distributed-cache variant). Neither can be affected by a PR that only adds 05136_key_condition_lowcardinality_key_over_merge; I re-ran the two failed jobs only.

@groeneai, investigate the failure: https://github.com/ClickHouse/clickhouse-private/actions/runs/34762093395/job/103737190142 (04321_table_readonly_background_merges, "writable control table TTL did not run in the background") and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The accounting fix for the mechanism that produces this exact message is already open: #111925. It is still needed on master: StorageMergeTree::selectPartsToMerge books the max_number_of_merges_with_ttl_in_pool slot at selection time and only two paths return it (the catch around the tagger, and the !scheduled branch in scheduleDataProcessingJob), so the pending-queue removal that DROP/DETACH TABLE performs on a merge still queued in the background pool leaks it. Each leaked slot permanently lowers the number of TTL merges the server can run, and at the limit no table with the default limit gets a TTL merge again.

I cannot open the job you linked: my account gets 404 on ClickHouse/clickhouse-private, so everything below comes from the public sources and public CI.

Public CI gives me no signal for this occurrence. Over the last 30 days this test has 0 failures in 12,399 recorded runs of Stateless tests (amd_debug, parallel) and 0 in 9,762 of Stateless tests (amd_debug, distributed plan, s3 storage, parallel). Its last public red was on 2026-08-06, on the #96130 branch, whose per-query DETACH/ATTACH hook widened exactly the leak window above, and that hook is not on master.

There is one hole in the test that I can close without the log. merge_with_ttl_allowed compares a server-global counter against a per-table limit: MergeTreeData::getTotalMergesWithTTLInMergeList(), which is the single MergeList::merges_with_ttl_counter, against this table's max_number_of_merges_with_ttl_in_pool, and MergeSelectorApplier::chooseMergesFrom gates every TTL merge on it, the part drop included. 04321 leaves that setting at its default of 2 on both TTL tables, so two concurrent TTL merges on any other table in the same parallel-run server are enough to keep the writable control table's expired part undropped for the whole 60 second window, with no leak involved. The same coupling makes the negative assertion vacuous: readonly ttl rows: 2 also passes when no table in the server could schedule a TTL merge at all.

Separate pull request from me: pin max_number_of_merges_with_ttl_in_pool high on both TTL tables of 04321, the way 02293_part_log_has_merge_reason already does for the same reason, and dump system.parts and system.merges when either wait times out, so the next red is attributable from the test output alone. I will link it here.

If the private artifacts show the expired part was never dropped long after the test finished, then the cause is the leaked slot rather than the pool limit, and #111925 is the fix for it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Opened #119884 for the 04321_table_readonly_background_merges failure: it pins max_number_of_merges_with_ttl_in_pool on both TTL tables, since that limit is per-table but the count it is compared against is the server-global MergeList::merges_with_ttl_counter with a default of 2, and it dumps system.parts and system.merges on a wait timeout so the next red is attributable from the test output alone. Test-only, .reference unchanged.

alexey-milovidov and others added 5 commits September 14, 2026 09:16
…ion` over `Merge` test

Address review: through `Merge` the array `CAST` keeps this query off the
`applyFunction` path (confirmed earlier with an instrumented binary: the
recursive-strip branch it was written for never fires), and with only
`count()` as the oracle a full scan or a declined chain passes too. The
direct `Array(LowCardinality(...))` arithmetic case is already covered by
`04141_array_lowcard_arithmetic_monotonicity`, so the block added no
regression coverage.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Four sentences prescribed a repair that master did not take, so they read against
the code a reader would go on to open.

`applyMonotonicFunctionsChainToRange` normalizes the chain's seed type
(`KeyCondition.cpp:5599-5601`) instead of each caller, `applyFunctionForField`
builds its const column on the running type it is handed (`:1627`, `:1607-1619`),
and the cached branch normalizes the chain's input only, deliberately keeping every
interior link's own result representation (`:1650-1662`).

State that invariant instead. The scenarios, the statements and the reference are
unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
…pins

Both OR arms asked for `b = 1`, so partition pruning removed the other partition
before primary-key analysis ran, and the granule line read `52/500` whether or not
the constant-coordinate bound on `b` was used, and whether or not the chain was
applied at all. The setting the statement pins was inert.

Ask for different `b` values instead. Min-Max and Partition then prune nothing, so
`PrimaryKey` pruning is left to the bound on `b`: `52/1000` with it, the
leading-key-only `103/1000` without. Two mutations now fail the test, where before
neither did: setting `use_partition_minmax_for_primary_key_pruning = 0`, and
replacing the `CAST` chain with `sipHash64(b)` so the chain is declined.

Also execute the predicate with the index, beside the existing no-index run. The
granule line is only explained, so nothing asserted that the pruning it reports
loses no rows. Both return 51.

Co-Authored-By: Claude Opus 5 <[email protected]>
…iant

Chain construction advances the argument type to each link's result type
(`KeyCondition.cpp:3413`) and execution does the same (`:5654`), so after
`toLowCardinality(b)` the running type is LowCardinality, never the plain key type
the comment claimed. State what the two statements really pin: normalizing past the
chain's seed is what would break them.

The other block called itself the `DENSE` path, which now reads as the dense
primary-key overload; the property it exercises is the block-backed `FieldRef` that
reaches `applyFunction`'s cache, in either overload. Name that instead.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ntations

The file pins `use_lightweight_primary_key_index_analysis = 1` for the sparse blocks
and the setting is session-wide, so the cached-column block only ever ran the
lightweight implementation while the header called it the dense path.

Run its granule assertion once more with the setting at 0. The chain reaches
`applyFunction` under either implementation, because both build block-backed
`FieldRef`s from the in-memory index
(`MergeTreeDataSelectExecutor.cpp:2341-2364` and `:2384-2405`), and both prune to
`Granules: 1/13` here. Pointing the new statement at `notEmpty(v)` turns its `1`
into `0`, so it is live.

Also drop `dense` from the header's list of pinned paths: it named an
implementation of primary-key analysis rather than the path through the chain.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 64c9b97 on top of your drop: same conclusion on the array block, so I discarded my own commit for it. Three changes to the blocks that stayed, tests only.

The sparse block's granule assertion was inert. Both OR arms asked for b = 1, so partition pruning removed the other partition before primary-key analysis ran, and the line read Granules: 52/500 with use_partition_minmax_for_primary_key_pruning at 1, at 0, and with the CAST chain replaced by sipHash64(b) so the chain is declined. The arms now ask for different b values: Min-Max and Partition prune nothing, and PrimaryKey reads 52/1000 with the constant-coordinate bound on b, against the leading-key-only 103/1000 without it. Both of those mutations now fail the test.

That granule line is only explained, never executed, so the predicate now also runs with the index, beside the existing no-index run. Both return 51.

The cached-column block only ever ran the lightweight implementation, because the file pins use_lightweight_primary_key_index_analysis = 1 session-wide. It now asserts pruning under both (Granules: 1/13 either way; pointing the new statement at notEmpty(v) turns its 1 into 0).

I also rewrote four comments that prescribed stripping LowCardinality in the sparse caller, in applyFunctionForField, and past the chain's seed. Master normalizes the seed only (KeyCondition.cpp:5601) and advances the argument type to each link's own result type (:3413, :5654), so they described a repair that is not in the tree.

20 of 20 runs pass with randomization on a debug build at this head. I did not squash: that would need a force-push over your commits.

…ion cache

`filterPartsByQueryConditionCache` gates only on `use_query_condition_cache`, the
analyzer, `apply_deleted_mask`, a filter DAG, vector search, FINAL and mutations
(`MergeTreeDataSelectExecutor.cpp:1651-1658`); none of `use_primary_key`,
`use_partition_pruning` or `use_skip_indexes` appears. So the control arm consults
the cache under a predicate the arm above it just executed, and the runner
randomizes `use_query_condition_cache` (`tests/clickhouse-test:1837`).

Today the two arms do not in fact share a verdict: the exclusions produced by index
analysis are written under `getSkipIndexProfiledConditionHash`, which folds in
`indexes.use_skip_indexes` (`MergeTreeDataSelectExecutor.cpp:1552`), and the control
sets that to 0 while the arm above runs with the default 1. Measured on a server with
the cache primed, the control reads 1000 of 1000 marks with 0 cache hits, exactly what
it reads on a cold cache. Align the two arms on `use_skip_indexes` and it instead
reads the indexed arm's 52 marks with 2 hits, so the reuse is real and only a salt in
another subsystem keeps it away from this test. With the cache pinned off the control
reads 1000 marks in that configuration too.

The bare condition hash is not a route for it either way: entries start all-matching
and `write()` only clears the ranges it is given, which are the ones a reader actually
evaluated, so a granule index analysis excluded is never cleared.

Pinned per statement rather than file-wide, so the other nine executed statements keep
running with the randomized value. The `Granules:` oracles are unaffected: in the
`SELECT ... FROM (EXPLAIN indexes = 1 ...)` form they report 1000/1000 with a primed
cache, identical to the cache off.

Reference unchanged. 20/20 with randomization, and the pair still reddens: moving the
indexed arm to `a >= 950` fails 2/2 with `-51 / +26`.

Co-Authored-By: Claude Opus 5 <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 14, 2026
Merged via the queue into ClickHouse:master with commit 8f68f32 Sep 14, 2026
177 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 14, 2026
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Sep 19, 2026
…erge slot count

max_number_of_merges_with_ttl_in_pool is a per-table setting, but
StorageMergeTree::selectPartsToMerge compares it against
MergeTreeData::getTotalMergesWithTTLInMergeList(), which returns the single
per-server MergeList::merges_with_ttl_counter, and MergeSelectorApplier gates
every TTL selector, TTLPartDropMergeSelector included, behind that comparison.
The setting defaults to 2, so two concurrent TTL merges on any other table in
the same parallel-run server keep this test's writable control table from
dropping its expired part for the whole 60 s window, which is the
"writable control table TTL did not run in the background" failure. The same
predicate also makes the following negative assertion pass for the wrong
reason: "readonly ttl rows: 2" holds just as well when no table in the server
could have scheduled a TTL merge at all.

Pin the setting on both TTL tables so the assertions depend only on this
test's own tables, as 02293_part_log_has_merge_reason.sh and
01921_concurrent_ttl_and_normal_merges_zookeeper_long.sh already do for the
same reason. Measured on a debug build: with the pin the expired part is
dropped while two TTL merges from another database hold the counter, without it
the drop is not selected until the counter frees.

Dump system.parts and system.merges on a wait timeout, on the failure path
only, so the next red says which of the three causes it was: other tables
holding the global TTL slots, a pool busy with something else, or nothing ever
selected for these tables.

Requested by @ alexey-milovidov in
ClickHouse#110326 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... and removed comp-testing Test content only (no production code). labels Nov 22, 2026
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-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... groeneai-origin-unknown PR origin: unclassified (legacy task) pr-not-for-changelog This PR should not be mentioned in the changelog 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.

3 participants