Skip to content

Make the "Inconsistent KeyCondition behavior" logical error actionable - #108011

Merged
alexey-milovidov merged 6 commits into
masterfrom
improve-inconsistent-keycondition-diagnostics
Jul 1, 2026
Merged

alexey-milovidov merged 6 commits into
masterfrom
improve-inconsistent-keycondition-diagnostics

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 20, 2026 •

Copy link
Copy Markdown
Member

Related: #90461
Related: #98075

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

Make the debug-only Inconsistent KeyCondition behavior logical error actionable by logging the offending KeyCondition, part and mark ranges.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Description / motivation

MergeTreeDataSelectExecutor::markRangesFromPKRange raises the LOGICAL_ERROR
Inconsistent KeyCondition behavior (debug builds only, guarded by #ifndef NDEBUG)
when KeyCondition::matchesExactContinuousRange reports a single exact continuous
range, but the binary-search result range turns out not to be exactly continuous.
This is the deliberate canary for functions reporting inaccurate monotonicity,
tracked in #90461 (the sibling NaN/Nullable-key case #98075 was already fixed by
#98964).

The message carried no context whatsoever, so every stress-test / fuzzer occurrence
was opaque — there was no way to tell which KeyCondition, part, or mark range
triggered it. This PR logs the key condition, the part name, the relaxed flag, and
the offending mark ranges right before throwing.

The thrown exception message is deliberately kept byte-for-byte unchanged. CI
derives the failure's name from the exception's format string
(ci/jobs/scripts/log_parser.py), so keeping the message constant preserves the
existing grouping under Logical error: Inconsistent KeyCondition behavior; the
high-cardinality details land in clickhouse-server.err.log instead, which is a
captured CI artifact.

There is no behavior change in release builds: the branch is compiled out under
NDEBUG, and the suspect range is excluded from exact_ranges exactly as before
(query results are unaffected).

CI report (failing test history) provided in the task:
https://play.clickhouse.com/play?user=play&run=1#V0lUSAogICAgOTAgQVMgaW50ZXJ2YWxfZGF5cwpTRUxFQ1QKICAgIHRvU3RhcnRPZkRheShjaGVja19zdGFydF90aW1lKSBBUyBkYXksCiAgICBjb3VudCgpIEFTIGZhaWx1cmVzLAogICAgZ3JvdXBVbmlxQXJyYXkocHVsbF9yZXF1ZXN0X251bWJlcikgQVMgcHJzLAogICAgYW55KHJlcG9ydF91cmwpIEFTIHJlcG9ydF91cmwKRlJPTSBjaGVja3MKV0hFUkUgKG5vdygpIC0gdG9JbnRlcnZhbERheShpbnRlcnZhbF9kYXlzKSkgPD0gY2hlY2tfc3RhcnRfdGltZQogICAgQU5EIHRlc3RfbmFtZSA9ICdMb2dpY2FsIGVycm9yOiBJbmNvbnNpc3RlbnQgS2V5Q29uZGl0aW9uIGJlaGF2aW9yIChTVElEOiA1MTgyLTJmMjcpJwogICAgLS0gQU5EIGNoZWNrX25hbWUgPSAnU3RyZXNzIHRlc3QgKGFybV9kZWJ1ZyknCiAgICBBTkQgdGVzdF9zdGF0dXMgSU4gKCdGQUlMJywgJ0VSUk9SJykKICAgIEFORCAocHVsbF9yZXF1ZXN0X251bWJlciA9IDAgT1IgYmFzZV9yZWYgSU4gKCdtYXN0ZXInKSkKICAgIEFORCB0ZXN0X2NvbnRleHRfcmF3IExJS0UgJyVFeGNlcHRpb246JScKR1JPVVAgQlkgZGF5Ck9SREVSIEJZIGRheSBERVNDCg==

🤖 Generated with Claude Code

Version info

  • Merged into: 26.7.1.361 (included in 26.7 and later)

`MergeTreeDataSelectExecutor::markRangesFromPKRange` throws the
`LOGICAL_ERROR` "Inconsistent KeyCondition behavior" (debug builds only,
guarded by `#ifndef NDEBUG`) when `KeyCondition::matchesExactContinuousRange`
reports a single exact continuous range but the binary-search result range
turns out not to be exactly continuous. This is the canary for functions
reporting inaccurate monotonicity tracked in
#90461.

The message carried no context, so each stress-test / fuzzer occurrence was
opaque: there was no way to tell which `KeyCondition`, part, or mark range
triggered it. Log the key condition, the part name, the relaxed flag, and the
offending mark ranges right before throwing.

The thrown exception message is deliberately kept byte-for-byte unchanged. CI
derives the failure name from the exception's format string (see
`ci/jobs/scripts/log_parser.py`), so keeping the message constant preserves the
existing grouping (`Logical error: Inconsistent KeyCondition behavior`); the
high-cardinality details go to `clickhouse-server.err.log` instead, which is a
captured CI artifact.

No behavior change in release builds (the branch is compiled out under
`NDEBUG`; the suspect range is excluded from `exact_ranges` as before).

Failing test history:
https://play.clickhouse.com/play?user=play&run=1#V0lUSAogICAgOTAgQVMgaW50ZXJ2YWxfZGF5cwpTRUxFQ1QKICAgIHRvU3RhcnRPZkRheShjaGVja19zdGFydF90aW1lKSBBUyBkYXksCiAgICBjb3VudCgpIEFTIGZhaWx1cmVzLAogICAgZ3JvdXBVbmlxQXJyYXkocHVsbF9yZXF1ZXN0X251bWJlcikgQVMgcHJzLAogICAgYW55KHJlcG9ydF91cmwpIEFTIHJlcG9ydF91cmwKRlJPTSBjaGVja3MKV0hFUkUgKG5vdygpIC0gdG9JbnRlcnZhbERheShpbnRlcnZhbF9kYXlzKSkgPD0gY2hlY2tfc3RhcnRfdGltZQogICAgQU5EIHRlc3RfbmFtZSA9ICdMb2dpY2FsIGVycm9yOiBJbmNvbnNpc3RlbnQgS2V5Q29uZGl0aW9uIGJlaGF2aW9yIChTVElEOiA1MTgyLTJmMjcpJwogICAgLS0gQU5EIGNoZWNrX25hbWUgPSAnU3RyZXNzIHRlc3QgKGFybV9kZWJ1ZyknCiAgICBBTkQgdGVzdF9zdGF0dXMgSU4gKCdGQUlMJywgJ0VSUk9SJykKICAgIEFORCAocHVsbF9yZXF1ZXN0X251bWJlciA9IDAgT1IgYmFzZV9yZWYgSU4gKCdtYXN0ZXInKSkKICAgIEFORCB0ZXN0X2NvbnRleHRfcmF3IExJS0UgJyVFeGNlcHRpb246JScKR1JPVVAgQlkgZGF5Ck9SREVSIEJZIGRheSBERVNDCg==

Related: #90461
Related: #98075

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

clickhouse-gh Bot commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ab7231f]

Summary: ✅


AI Review

Summary

This PR augments the debug-only Inconsistent KeyCondition behavior path in MergeTreeDataSelectExecutor::markRangesFromPKRange to log the part, mark ranges, primary KeyCondition, and useful optional _part_offset / total-offset KeyConditions before preserving the existing LOGICAL_ERROR. The current code addresses the prior bot finding, and I did not find new correctness, safety, or metadata issues.

Missing context / blind spots
  • ⚠️ The newest CI run for ab7231f0e22 was still in progress while reviewing (Fast test, Code Review, and Build (arm_tidy) had not completed in GitHub status); the available Praktika report had no failed tests. A complete green run would close this gap.
Final Verdict

✅ No new inline findings. The existing bot-authored thread is already resolved and the current code no longer has that diagnostic coverage gap.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jun 20, 2026
@nihalzp nihalzp self-assigned this Jun 20, 2026
…havior" diagnostic

The diagnostic logged only the primary `key_condition`, but the binary-search path
in `markRangesFromPKRange` is taken only when every useful condition reported an
exact continuous range, and `check_in_range` combines `key_condition`,
`part_offset_condition` and `total_offset_condition`. A bad `_part_offset` or
total-offset condition can therefore trip the throw while `key_condition` is empty
or unrelated, leaving the log non-actionable.

Log every participating condition (with its `useful` and `relaxed` flags) so the
occurrence is actionable for all callers of this path, not just for queries that
exercise the primary key condition.

Addresses review feedback.

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

Copy link
Copy Markdown
Member Author

@groeneai, fix the error found by fuzzer: Logical error: Bad cast from type A to B (STID: 3721-419e)

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov Triaged STID 3721-419e.

Error: Bad cast from DB::ColumnNullable to DB::ColumnString in SingleValueDataString::setIfSmaller (i.e. minSimpleState / min over a String), via AggregateFunctionSimpleState::add → Aggregator::executeWithoutKeyImpl.

Reproducer (exact, AST fuzzer amd_msan — report):

SELECT minDistinct(c0 >= (SELECT minSimpleState(*) FROM (SELECT DISTINCT toLowCardinality('1') GROUP BY GROUPING SETS ((1))))) FROM (SELECT 1 AS c0 LIMIT 197) AS t0 SETTINGS group_by_use_nulls = 1;

The crashing aggregate is the inner minSimpleState(*) over the GROUP BY GROUPING SETS subquery.

Root cause family: group_by_use_nulls = 1 makes the grouping key Nullable, but the minSimpleState aggregate stays bound to the non-nullable SingleValueDataString state, so at execution it receives a ColumnNullable and assert_cast<ColumnString> aborts. Same class as #91119, which I have open in PR #104350 — but this variant is non-correlated and uses GROUPING SETS, so I am verifying whether the current fix covers it and will extend it plus add a regression test.

@groeneai

Copy link
Copy Markdown
Collaborator

Fixed. STID 3721-419e is the constant-LowCardinality variant of the #91119 group_by_use_nulls family. ConstantNode::convertToNullable used makeNullableSafe, which is a no-op on LowCardinality(T) (it cannot be inside Nullable), so a constant LowCardinality GROUP BY key stayed non-Nullable while its runtime rollup/grouping-sets rows were NULL; the outer minSimpleState/min over a String then bad-cast ColumnNullable to ColumnString. ColumnNode and FunctionNode already used the LC-aware makeNullableOrLowCardinalityNullableSafe; ConstantNode was the only one that did not.

Fix + regression test pushed to my existing #91119 PR #104350 (commit ec6b58a), since it is the same family and same file. Both directions verified locally (aborts on master, passes patched; the projected type is now LowCardinality(Nullable(String))).

pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Jun 29, 2026
…om `04338_on_fly_mutation_read_overwritten_lc_source`

The stateless test `04338_on_fly_mutation_read_overwritten_lc_source`
(table `t_overwrite_before_consume`) chains the async mutations
`UPDATE v = toString(id + 100)`, `UPDATE b = isNotNull(materialize(v))`
and `MODIFY COLUMN v UInt64` over a column whose on-disk value is the
unconvertible String `'x'`. This is an intentionally-broken mutation of
exactly the class already documented in the `CANNOT_PARSE_TEXT` allowlist
(issue ClickHouse#39174): a `MODIFY COLUMN ... UInt64` on un-parseable String data,
just like the already-allowlisted `'Hello'`/`'a'`/`'b'` variants from
`00834_kill_mutation` and `01414_mutations_and_errors_zookeeper`.

After the upgrade restart the broken mutation is retried and logs
`Cannot parse string 'x' as UInt64: syntax error at begin of string`
(`CANNOT_PARSE_TEXT`) to `clickhouse-server.upgrade.log`, which fails the
`Upgrade check` with `Error message in clickhouse-server.log (see
upgrade_error_messages.txt)`. This is not a backward-incompatibility or a
regression; it is the expected test-induced error.

Add the narrow `'x'` message to the upgrade-check allowlist and document
`04338` in the comment block. The failure is not caused by any product
change - it surfaces on any pull request that runs the Upgrade check
(observed on PR ClickHouse#108011 and the unrelated PR ClickHouse#107433).

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

Copy link
Copy Markdown
Member Author

Merged the latest master (222 commits) into the branch — clean merge, no conflicts; the net diff is unchanged (MergeTreeDataSelectExecutor.cpp, +35/-1). Verified the debug-only #ifndef NDEBUG diagnostic branch still type-checks against current master via a -fsyntax-only -UNDEBUG compile (exit 0, no warnings); the change remains a no-op in release builds.

The only red checks are Stress test (amd_tsan) and Stress test (arm_tsan) — both Hung check failed, possible deadlock found, the chronic master-wide flake tracked in #107941 (this PR is compiled-out in release and the TSan diagnostic addition is unrelated to a deadlock). The push re-triggers CI to give the flaky stress run another pass. PR is approved (nihalzp) with an AI Review ✅ and no open review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Reviewed the current state via /continue-pr.

Status: MERGEABLE, mergeStateStatus: UNSTABLE (non-required stress checks only). Approved by nihalzp and AI Review ✅; no open review threads. Net diff unchanged: MergeTreeDataSelectExecutor.cpp, +35/-1, debug-only (#ifndef NDEBUG), one changed C++ line, 100% covered.

The only red checks are unrelated — Hung check failed, possible deadlock found on Stress test (amd_debug), (amd_tsan) and (arm_tsan):

  • All three are the chronic master-wide flake #107941 (OPEN); the CI summary links each occurrence to it directly.
  • The hung stacks are generic QueryAnalyzer/InterpreterSelectQueryAnalyzer frames — no KeyCondition / markRangesFromPKRange / MergeTreeDataSelectExecutor frame, so they cannot be tied to this change.
  • The change only adds a LOG_ERROR immediately before an already-existing throw in a branch that is compiled out in release builds (and the TSan configs don't exercise this debug-only path), so it cannot introduce a deadlock.

The earlier fuzzer finding (Bad cast STID 3721-419e) was triaged by @groeneai and fixed separately in #104350 — it is not a failure of this PR's current CI.

I re-ran the failed stress jobs to give the flaky Hung check another pass. No code change is needed and no master re-merge (merge-base is <1 day old and the red is not fixed on master).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged the latest master into the branch (clean, no conflicts; new head ab7231f0e22).

Re-merging (rather than only re-running the flaky stress jobs, as before) because the situation changed since my last pass:

  • master has since evolved the very file this PR touches — MergeTreeDataSelectExecutor.cpp gained the top_k_filter_info cache-key salting in filterPartsByQueryConditionCache — so a re-merge revalidates the change against the current file (the previous merge-base predated that).
  • The branch was ~615 commits behind and red, and repeated re-runs of the same binary kept landing on the chronic Hung check failed, possible deadlock found flake (#107941). A fresh merge produces a new binary and a fresh CI pass, which is the realistic way to give that timing-dependent flake another roll.

Verified after the merge:

  • Net diff of this PR is unchanged: MergeTreeDataSelectExecutor.cpp, +35/-1, entirely under #ifndef NDEBUG (no release/TSan behavior change), and the thrown "Inconsistent KeyCondition behavior" message is byte-identical (so CI still groups the failure under one stable name).
  • The added LOG_ERROR is in markRangesFromPKRange; master's changes were confined to the separate filterPartsByQueryConditionCache function, and every local the diagnostic references (key_condition_useful, part_offset_condition_useful/part_offset_condition, total_offset_condition_useful/total_offset_condition, part_name, result_range, result_exact_range) still resolves in the merged function.

The only prior red checks were the two TSan stress jobs, both the #107941 hung-check flake (CI auto-links each occurrence to it; the hung stacks are generic QueryAnalyzer/InterpreterSelectQueryAnalyzer frames with no KeyCondition/markRangesFromPKRange frame, and this branch is compiled out in release/TSan). Approved by nihalzp and AI Review ✅, no open review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Follow-up on the re-merge: the fresh CI run on ab7231f0e22 is green so far — 0 failures, and crucially the previously-failing stress jobs now pass:

  • Stress test (amd_tsan) ✅, Stress test (arm_tsan) ✅ — plus all other Stress test (...) variants ✅.

So the re-merge did clear the chronic Hung check failed, possible deadlock found flake (#107941) that was the sole prior blocker; it did not re-hit on the new binary. The remaining stateless / integration / performance jobs are all green so far (102 checks passed, the rest in progress).

Net diff is unchanged: MergeTreeDataSelectExecutor.cpp, +35/-1, debug-only (#ifndef NDEBUG), thrown message byte-identical. No re-merge needed now (merge-base cb507a96d4f is <1 day old, only 19 commits behind, and CI is green). MERGEABLE; approved by nihalzp and AI Review ✅; no open review threads.

@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.50% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.70% 77.70% +0.00%

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

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 1, 2026
Merged via the queue into master with commit 92b2b8c Jul 1, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the improve-inconsistent-keycondition-diagnostics branch July 1, 2026 17:40
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 1, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…om `04338_on_fly_mutation_read_overwritten_lc_source`

The stateless test `04338_on_fly_mutation_read_overwritten_lc_source`
(table `t_overwrite_before_consume`) chains the async mutations
`UPDATE v = toString(id + 100)`, `UPDATE b = isNotNull(materialize(v))`
and `MODIFY COLUMN v UInt64` over a column whose on-disk value is the
unconvertible String `'x'`. This is an intentionally-broken mutation of
exactly the class already documented in the `CANNOT_PARSE_TEXT` allowlist
(issue ClickHouse#39174): a `MODIFY COLUMN ... UInt64` on un-parseable String data,
just like the already-allowlisted `'Hello'`/`'a'`/`'b'` variants from
`00834_kill_mutation` and `01414_mutations_and_errors_zookeeper`.

After the upgrade restart the broken mutation is retried and logs
`Cannot parse string 'x' as UInt64: syntax error at begin of string`
(`CANNOT_PARSE_TEXT`) to `clickhouse-server.upgrade.log`, which fails the
`Upgrade check` with `Error message in clickhouse-server.log (see
upgrade_error_messages.txt)`. This is not a backward-incompatibility or a
regression; it is the expected test-induced error.

Add the narrow `'x'` message to the upgrade-check allowlist and document
`04338` in the comment block. The failure is not caused by any product
change - it surfaces on any pull request that runs the Upgrade check
(observed on PR ClickHouse#108011 and the unrelated PR ClickHouse#107433).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…tent-keycondition-diagnostics

Make the "Inconsistent KeyCondition behavior" logical error actionable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-ci 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.

4 participants