Skip to content

Do not build a key range from a constant holding a NULL inside an Array, Map or JSON - #124700

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/key-condition-null-in-array-map-constant
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/key-condition-null-in-array-map-constant

Conversation

@groeneai

@groeneai groeneai commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #100535
Related: #118944

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

Fixed rows being silently dropped by partition pruning, primary key analysis or a minmax skip index when a comparison constant is an Array, Map or JSON value that holds a NULL. For example, SELECT count() FROM t WHERE NOT (a > [NULL]) over a table PARTITION BY a with an Array(String) column returned 0 instead of the number of rows.

Description

Found by the AST fuzzer TLP oracle on #100535 (report).

CREATE TABLE t (a Array(String)) ENGINE = MergeTree PARTITION BY a ORDER BY tuple();
INSERT INTO t VALUES (['x']), (['y']), (['x', 'z']);
SELECT count() FROM t WHERE NOT (a > [NULL]);

On 26.3.42.3, 26.8.18.2 and master this returns 0 instead of 3 (3 with use_partition_pruning = 0).

Array, Map and JSON values compare with IColumn::compareAt, which orders a NULL element after every value (['x'] < [NULL] is 1). Key ranges are ordered by Field, which puts Null before every value, so the atom a in (-Inf, [NULL]] excludes every non-empty array. The same happens for a primary key or a minmax index on Array(Nullable(String)), a minmax index on JSON, and a Tuple key with an Array element.

The atom is now declined when the converted constant holds such a NULL, at the same place where a NaN in a constant is already declined (#116763). A NULL directly inside a Tuple is a different, three-valued case handled by #118944.

The new test fails on master (20/20 randomized runs) and passes 50/50 here; removing the new condition makes it fail again. Constants without a NULL prune exactly as before, which the test also checks.

🤖 Generated with Claude Code


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

…ay, Map or JSON

`Array`, `Map` and `JSON` values compare with `IColumn::compareAt`, which orders
a `NULL` element after every value (`['x'] < [NULL]` is 1), while `Field` order,
which orders the endpoints of a key range, puts `Null` before every value. For a
comparison constant such as `[NULL]` the range `(-Inf, [NULL]]` then excludes
every non-empty array, so partition pruning, the primary key and `minmax` skip
indexes dropped rows: on a table `PARTITION BY a` over `Array(String)`,
`WHERE NOT (a > [NULL])` returned 0 rows instead of all of them.

Decline the atom when the converted constant holds such a `NULL`, at the same
place where a `NaN` in a constant is already declined. A `NULL` directly inside
a `Tuple` is not screened here: a tuple comparison is three-valued, which is a
different case.

Found by the AST fuzzer TLP DISTINCT oracle on ClickHouse#100535.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 8, 2026
@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold review (2 nits).

# Sev Finding Verdict Evidence / action
1 💡 Equality atoms (=, !=, <=>) whose constant holds a nested NULL are declined too, so they lose pruning DISAGREE Only pruning is lost; such a point endpoint is still Field-ordered against compareAt-ordered mark bounds, so keeping it would need its own proof. Results are correct both before and after.
2 💡 The guard walks a container constant twice DROPPED Once per atom at analysis time, on a parser-bounded constant; not measurable.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-10:20261008-173200

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: NOT (a > [NULL]) over PARTITION BY a (Array(String)) returns 0 instead of 3 on every run, on master, 26.3.42.3 and 26.8.18.2.
b Root cause explained? compareAt orders a nested NULL last, Field order (key range endpoints) puts it first, so (-Inf, [NULL]] excludes every non-empty array.
c Fix matches root cause? Yes: the atom is declined where the converted constant becomes a range endpoint, next to the existing NaN guard, so every KeyCondition consumer is covered.
d Test intent preserved / new tests added? New SQL test: one line per carrier that is wrong on master, plus a control that a NULL-free constant still prunes.
e Both directions demonstrated? Master 20/20 FAIL, this PR 50/50 OK (randomized); without the new condition the test fails again.
f Fix is general across code paths? Partition pruner, partition minmax, primary key, minmax skip index and trivial count all go through extractAtomFromTree; IN / NOT IN sets and transformed keys were measured correct on master.
g Fix generalizes across inputs (params/datatypes/wrappers)? Array, Map, JSON, Array(JSON), Array(Nullable(String)), Tuple with an Array element, multi-column keys; <, <=, NOT >, =, !=, isNotDistinctFrom.
h Backward compatible? (maintainer-approved exception only) Yes: no setting or format change; only predicates whose constant holds such a NULL lose pruning.
i Invariants and contracts preserved? A range atom exists only when its endpoint orders like the SQL comparison; declining takes the existing FUNCTION_UNKNOWN path.

Session id: cron:clickhouse-impl-slot-4:20261008-164058

@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [373b11b]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, sequential) FAIL
05339_iceberg_top_k_query_condition_cache FAIL cidb
Stateless tests (amd_debug, distributed plan, s3 storage, sequential) FAIL
05339_iceberg_top_k_query_condition_cache FAIL cidb
Stateless tests (arm_binary, sequential) FAIL
05339_iceberg_top_k_query_condition_cache FAIL cidb
Stateless tests (arm_asan_ubsan, azure, sequential, 2/2) FAIL
05339_iceberg_top_k_query_condition_cache FAIL cidb
Stateless tests (arm_binary, s3 storage, DBReplicated, sequential) FAIL
05339_iceberg_top_k_query_condition_cache FAIL cidb
Stateless tests (arm_binary, ParallelReplicas, s3 storage, sequential) FAIL
05339_iceberg_top_k_query_condition_cache FAIL cidb
Stateless tests (arm_binary, AsyncInsert, s3 storage, sequential) FAIL
05339_iceberg_top_k_query_condition_cache FAIL cidb
01168_mutations_isolation_3 NOT_FAILED cidb

AI Review

Summary

Reviewed #124700 at 373b11bcca1e95caeb9c887c003ba65183164307. The change prevents incorrect pruning when comparison constants contain NULL inside an Array, Map, or JSON, including nested containers. No actionable findings.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build was available to independently run 05339_key_condition_null_in_array_map_constant. The PR records successful regression runs, but functional CI results for the current head were not yet available. Completion of those jobs would close this validation gap.
Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 8, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 8, 2026
@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 36167c0

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
Integration tests (amd_msan, targeted) / test_storage_nats/test_nats_jet_stream.py::test_nats_jet_stream_skipped_broken_message_is_not_redelivered_after_reconnect[hard_kill] flaky, not from this PR (which only changes KeyCondition range atoms): AssertionError: no streaming source performed an in-source recovery at line 1590. The test landed on 2026-10-07 and this is its only failure in 30 days (1 of 156 hard_kill runs on amd_msan in 3 days); the other run in this job passed a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR rollup, red only because of the row above a fix task is created (the same one, fixing-PR link to follow here)

All 152 check runs completed and Finish Workflow is green. CIDB has no other FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20261009-030006

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_nats_jet_stream_skipped_broken_message_is_not_redelivered_after_reconnect[hard_kill] failure: #124849

…ion-null-in-array-map-constant

# Conflicts:
#	src/Storages/MergeTree/KeyCondition.cpp
@clickhouse-gh

clickhouse-gh Bot commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 373b11bcc with master f5b8c2c15 (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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 373b11b

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_debug, sequential) / 05339_iceberg_top_k_query_condition_cache master breakage, not from this PR (it changes only KeyCondition range atoms; this is a different test from its own 05339_key_condition_null_in_array_map_constant, which passed): the test failed on every master commit from the #126987 merge 41d5f3406f9d until its revert, and the tested merge tree b30033f607d0 contains #126987 but not the revert #127378 (external, merged revert)
Stateless tests (amd_debug, distributed plan, s3 storage, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_asan_ubsan, azure, sequential, 2/2) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, AsyncInsert, s3 storage, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, s3 storage, DBReplicated, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Mergeable Check, PR praktika rollups of the rows above #127378 (the owner of the rows above)

Fast test, Style check, both Bugfix validation (functional tests, *) jobs, all five flaky checks and CH Inc sync passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261022-200007

@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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 19, 2026

This branch has not been deployed

No deployments
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-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant