Skip to content

Fix text and token skip indexes over-pruning a map element whose default matches the predicate - #119336

Open
groeneai wants to merge 20 commits into
ClickHouse:masterfrom
groeneai:fix-text-index-map-element-default-prune
Open

groeneai wants to merge 20 commits into
ClickHouse:masterfrom
groeneai:fix-text-index-map-element-default-prune

Conversation

@groeneai

@groeneai groeneai commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #113157

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 ngrambf_v1, tokenbf_v1 and sparse_grams skip indexes over mapKeys or mapValues returning too few rows for a predicate on a map key the row does not have, for example m['missing_key'] = '::' on a Map(String, IPv6) column: such a key reads as the map value type's default, so the row matches, while index analysis took that default from the compared constant's type and only tested equality, affecting every non-String map value type and patterns such as LIKE. Rows were also dropped for a map key containing a backslash, such as m['abc\\+def'] LIKE '%zzz%', tokenized as a pattern rather than as a literal. The same analysis raised Code: 170 BAD_GET on an array needle over a map element, such as hasAny(m['key'], ['a']).

Description

MergeTreeConditionBloomFilterText::traverseTreeEquals must decline the index when a row lacking the map
key would satisfy the predicate: the mapKeys probe is built from the key and misses in exactly that
granule. The old guard derived that default from the compared constant's type and tested only equality, so
it missed both non-String map value types and patterns such as m['nokey'] LIKE '%', in either spelling
(arrayElement, m.key_<key>).

It now evaluates the predicate against a default-valued instance of the column actually read, as the newer
text index does (MergeTreeIndexConditionText::traverseMapElementKeyNode). notEquals and notLike
build the mirrored granule mask, so they decline on the opposite condition.

That probe also replaces the needle with the key, which like, notLike and match tokenized as a
pattern, consuming escape characters while the index holds the key's raw bytes, so m['abc\\+def'] LIKE '%zzz%' loses the row on master. Those three now tokenize a substituted key literally.

The old guard also rejected an array needle as Array(String)'s default, and that rejection was
load-bearing: with the key substituted, hasAny, hasAll and multiSearchAny read that String as an
Array and raised Code: 170 BAD_GET; they now decline this carrier explicitly, as does a subscript
analysis may not evaluate, such as one calling sleep. A non-constant subscript it can evaluate keeps
the mapValues index. Neither loss can drop a row.

Validated by the extended test (both spellings, both carriers, two index types, with pruning controls) and
50 randomized runs.

#113157 has merged and this branch contains it; its narrower mapValues default guard is subsumed here.
MergeTreeIndexBloomFilter.cpp has the same defect class, left to #107076 and #117318.


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

groeneai and others added 9 commits September 10, 2026 09:12
A key that a row does not have reads as the map value type's default, both
through arrayElement(m, 'k') and through the equivalent m.key_<key> subcolumn.
Such a row therefore satisfies m[k] <op> c whenever <op>(default, c) holds, and
the probe a mapKeys index builds from the key misses in exactly that granule, so
index analysis has to decline.

MergeTreeConditionBloomFilterText::traverseTreeEquals asked a different question
twice over. It derived the default from the right-hand constant's type instead of
the accessed map value type, which coincide only when the map value is String, and
it compared them for equality even when the predicate was like, match, startsWith
or hasToken*. Rows were dropped for IPv6, IPv4, UUID, Date, DateTime, DateTime64,
UInt32, Int64, Float64, Decimal and FixedString map values, and for patterns the
default satisfies such as m['nokey'] LIKE '%'. The subcolumn spelling is the
default path, since optimize_functions_to_subcolumns is enabled.

Decide by executing the already-resolved predicate against a default-valued
instance of the column the sub-DAG reads, which is what the newer text index does
in MergeTreeIndexConditionText::traverseMapElementKeyNode. The answer then uses
the engine's own semantics rather than a byte-wise Field comparison, and the type
comes from the map instead of from the constant, so no default is ever named and
the guard no longer depends on the (incorrect) claim that arrayElement returns ''
for a missing key on LowCardinality(Nullable(String)).

The two atom families build mirrored granule masks: a matching atom claims
"nothing here matches" when the key term is absent and must decline when the
default matches, while notEquals and notLike claim "everything here matches" and
must decline when it does not. Testing only the first half changes the disposition
of notEquals atoms that master resolves correctly today, so the guard carries the
direction. The eligibility lookups are hoisted above it, so a map column without a
mapKeys or mapValues index is never evaluated.
Both mapValues arms compared a Map(String, String) element with '', which the
previous guard also declined, so neither would have noticed the mapValues half of
the new guard disappearing. bloomFilterIndexTextValidator accepts IPv6 alongside
String and FixedString, so Map(String, IPv6) with a mapValues index is creatable
and gives that half a shape that depends on the fix.

Spell the IPv6 default as 0:0:0:0:0:0:0:0 rather than ::, so that the probe has
trigrams at all. An ngrambf_v1(3, ...) probe over '::' yields no trigrams and
BloomFilter::contains(empty) is true, which keeps the granule regardless of the
guard. The 13 trigrams of the longer spelling are all 0:0 or :0:, and the
granule holds the raw 16 bytes of 2001:db8:1:2:3:4:5:6, so the probe misses.

Map(String, Nullable(String)) is the one shape whose index eligibility this
changes: a NULL default is not a match, so the index stays usable where the old
guard declined it. force_data_skipping_indices pins that, returning 0 here and
raising INDEX_NOT_USED without the fix.

Assert the granule count through count() > 0, as the other EXPLAIN indexes = 1
tests do, since parallel replicas add per-node Granules lines.

Co-Authored-By: Claude Opus 5 <[email protected]>
The removed default-equality guard also rejected an Array-typed needle, because
Array(String)->getDefault() is the empty array. That rejection was load-bearing:
the mapKeys path substitutes the map key for the needle, and the array-consuming
atoms (has with an array, hasAny, hasAll and multiSearchAny) then read that
String as an Array and raise BAD_GET. Evaluating the predicate instead admits
the atom, so multiSearchAny(m['nokey'], CAST([], 'Array(String)')) began failing
on a query that returned an empty result before.

Decline the index for an array needle whenever mapKeys is the carrier, above
both the substitution and the default evaluation. The check sits inside the two
map-element branches: an array needle on a plain column reaches getKeyIndex
directly and stays indexed, as 05081 and both 03375_bloom_filter_*_has_hasAny_
const_array assert.

The same guard also removes the BAD_GET for a non-empty array needle over a map
element, which master raises today.

Co-Authored-By: Claude Opus 5 <[email protected]>
optimize_functions_to_subcolumns defaults to 1, so the two unpinned arms only ever
reached the m.key_<serialized> subcolumn call site and left the mapValues carrier
untested through arrayElement. Both spellings return 0 against an oracle of 1
before the fix, so each of the four arms carries its own weight.

Co-Authored-By: Claude Opus 5 <[email protected]>
`mapElementDefaultBreaksIndex` mirrors its soundness condition for a
negating atom, and `negating` covers `notEquals` and `notLike`. Every
existing arm that depended on that mirroring used `notEquals`, and every
`like` arm compared against `LIKE '%'`, where declining the index is
also the correct answer. Two one-line changes to the helper therefore
left the whole suite green: dropping `notLike` from `negating`, and
making the helper always decline for `like`.

Three disposition arms close that gap. They assert through
`force_data_skipping_indices` because the counts are the same whether or
not the index is used: a `LIKE` the default cannot satisfy keeps
pruning, `NOT LIKE '%'` declines the index, and `NOT LIKE '%zzz%'`
keeps it usable.

The pattern is `'%zzz%'` rather than a prefix pattern on purpose.
`optimize_rewrite_like_perfect_affix` rewrites a perfect affix into
`startsWith` whenever the haystack is a column node, which is what the
default `optimize_functions_to_subcolumns = 1` produces for a map
subscript. `LIKE 'zzz%'` would therefore never reach the pattern
branches, and neither mutation above would redden.
The removed default-equality guard did a third job. It compared the constant
against its own type's default, so it declined every atom whose constant was
that default, including atoms on carriers whose probe cannot match the index at
all. Evaluating the predicate instead correctly admits m[key] = '' when the map
value type is Nullable(String), whose default is NULL, and that exposed the
carrier defect underneath.

In the map subcolumn branch the probe becomes the key serialized as text
(FunctionToSubcolumnsPass builds the suffix with serializeText), while the
aggregator tokenizes the key column's raw bytes. For a Map(IPv6, Nullable(String))
those differ, the probe for a present key matches nothing, and the granule
holding it is pruned: m[toIPv6('2001:db8:1:2:3:4:5:6')] = '' returned 0 instead
of 1. The arrayElement spelling was already declined by the pre-existing check
on the key constant's type, which is why only one spelling was wrong.

Decline the index when the indexed key type is neither String nor FixedString,
unwrapping Array and LowCardinality the way the index validator does. Master
over-prunes the same shape today for any constant that is not the value type's
default, so this also fixes a pre-existing wrong result. A FixedString key is
that representation and stays indexed.

Co-Authored-By: Claude Opus 5 <[email protected]>
On a `mapKeys` carrier both map-element branches replace the needle in
`const_value` with the map key, but the per-function tail then tokenized that
key with the tokenizer chosen for the original predicate:
`stringLikeToBloomFilter` for `like` / `notLike` and the extracted required
substring for `match`. `nextInStringLike` consumes escape characters, while the
aggregator indexes the key column's raw bytes, so a key containing a backslash
was probed for terms the granule cannot hold and the granule holding exactly
that key was pruned.

`like` / `notLike` / `match` on a substituted key now build the probe with
`stringToBloomFilter`, keeping the mask the tail would have produced. For a key
without `%`, `_` or a backslash the probe is byte-identical to today's, so no
existing disposition moves.

This also fixes a pre-existing over-prune: on `Map(String, String)` a pattern
the map value satisfies (`m['abc\\+def'] LIKE '%zzz%'`) already lost the row
before the map-element default guard existed.

`startsWith` / `endsWith` already delegate to `stringToBloomFilter` or drop
boundary-partial tokens, `hasToken*` already uses it, and `multiSearchAny` is
declined on this carrier, so those three functions are the complete set.

Co-Authored-By: Claude Opus 5 <[email protected]>
`mapElementDefaultBreaksIndex` executes a cloned sub-DAG of the atom to learn
whether the map value type's default satisfies the predicate. A subscript such
as `m[if(0 IN (SELECT number FROM numbers(1)), 'a', 'b')]` contributes no
ordinary input, so the single-required-column check still passed and the
evaluation went ahead with a `ColumnSet` that is only built later during query
execution; `FunctionIn` then raised `LOGICAL_ERROR "Not-ready Set is passed as
the second argument for function 'in'"` on a query the engine answers.

`MergeTreeIndexConditionText::traverseMapElementKeyNode` prepares every such
set before executing the same kind of sub-DAG and declines when it cannot. Do
the same here, taking the query context from the key node as the `IN` handling
in this file already does. The helper's polarity is inverted relative to the
sibling, so both "cannot prepare" exits return `true`, i.e. decline the index.

Co-Authored-By: Claude Opus 5 <[email protected]>
The four arms over the key `abc\+def` asserted only the row count, and that
count is also what index analysis declining the atom answers, so they could
not tell "the literal probe matches the indexed key" from "the index was not
used". Forcing the index makes each arm separate three states: probe matches
(1), granule over-pruned (0), atom declined (INDEX_NOT_USED).

Measured on three binaries with the same fixture: all four answer 1 here, the
pre-image of the literal-tokenization change answers 0, and the merge base
answers 0 on the `like` pair and raises INDEX_NOT_USED on the `match` pair.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Sep 10, 2026
@groeneai

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

Pre-publication review by an independent reviewer plus a second model (engine: codex), six rounds on
this diff: 5 findings AGREEd and fixed, 3 DISAGREEd with recorded evidence.

# Sev Finding Verdict Evidence / action
1 ❌ An array needle on a mapKeys probe read a String as an Array and raised Code: 170 BAD_GET AGREE, fixed array needles decline this carrier
2 ❌ The m.key_<key> spelling probed a non-String indexed key with its text spelling AGREE, fixed that shape declines
3 ❌ A substituted map key was tokenized as a pattern, losing the granule for a key holding an escape AGREE, fixed like, notLike and match tokenize a substituted key literally
4 ❌ A Set inside the subscript was read before it was built AGREE, fixed prepared first, as the text index does
5 ⚠️ The escaped-key arms passed whether the probe matched or the index was declined AGREE, fixed each of the four arms now forces the index, so it separates a matching probe (1) from an over-pruned granule (0) from a declined atom (INDEX_NOT_USED)
6 ⚠️ The result-type gate strips Nullable but not LowCardinality, so pruning master has would be lost on a LowCardinality-valued map DISAGREE measured before changing anything, and the premise does not hold: EXPLAIN QUERY TREE shows the predicate's result_type is plain UInt8 in both spellings, because arrayElement returns String and the subcolumn path inserts an explicit _CAST(m.key_abc, 'String'), so the extra unwrap would be a no-op. The arrayElement spelling answers 1 with the index forced. The one shape that does decline declines identically on the merge base, for a cause upstream of this gate (the node this class inspects is the _CAST, not the column), so it is not introduced here. No source change, and deliberately no test arm: it would assert the same result on this branch, on the pre-image and on the base alike
7 ⚠️ The change could be read as claiming a non-String indexed column is probed correctly DISAGREE out of scope here; the changelog states only what this changes, and #113157 covers the probe encoding
8 ⚠️ Evaluating the predicate can raise during index analysis where a fully pruned query answered 0 DISAGREE every predicate in that class is unevaluable for any row (match(x, '('), 'zzz' as an IPv6); the newer text index evaluates the same way with no catch, and the directive on #105848 removed a catch here to surface such errors at planning time. Happy to make it decline instead if you prefer

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

Session id: cron:clickhouse-review-self-slot-58:20260910-190900

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

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [948c745]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, azure, sequential) ERROR

AI Review

Summary

This PR teaches MergeTreeConditionBloomFilterText to decline mapKeys / mapValues skip-index pruning when a missing map key reads as a default that still satisfies the predicate, and it fixes several related substituted-key cases. The remaining problem is that the new default-value evaluator still trusts IN sets that the sibling text-index path explicitly rejects, so it can still make a one-shot pruning decision from mutable or setting-disabled sets.

Findings
  • ⚠️ Majors
    • [src/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp:625] mapElementDefaultBreaksIndex still only asks whether a ColumnSet is ready after buildOrderedSetInplace(). Unlike the sibling prepareSetsForDefaultValueEvaluation() helper in src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:1857, it does not reject future_set->isMutableDuringQuery() and it does not enforce use_index_for_in_with_subqueries = 0 for a prebuilt FutureSetFromSubquery. That means this one-shot default-value check can still depend on set contents that are allowed to change during the query, or on a subquery set the setting explicitly says skip-index analysis must not use. The author's reply reasons about key choices that all read the same map default, but mapValues does not require the subscript to stay a single non-NULL literal: a set-controlled branch between NULL and a real key still changes whether a missing element matches. [dismissed by author -- https://github.com/Fix text and token skip indexes over-pruning a map element whose default matches the predicate #119336#discussion_r3984361656]
    • Suggested fix: reuse the sibling helper, or mirror its isMutableDuringQuery() and use_index_for_in_with_subqueries guards before calling buildOrderedSetInplace() here.
Tests
  • ⚠️ Add a focused regression for a map-element predicate whose subscript depends on IN and can switch between NULL and a real key, plus a case with use_index_for_in_with_subqueries = 0, so this helper is pinned to the same set-eligibility contract as MergeTreeIndexConditionText.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: make mapElementDefaultBreaksIndex reject mutable storage sets and setting-disabled subquery sets the same way prepareSetsForDefaultValueEvaluation() does, then pin that contract with a regression test.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @shankar-iyer @ahmadov, could you review this? MergeTreeConditionBloomFilterText took the map value's default from the compared constant's type, so on a non-String map value type the guard never fired and the mapKeys probe pruned the granule holding a row whose missing key reads as that default (m['nokey'] = '::' on Map(String, IPv6) loses the row). It now evaluates the predicate against a default-valued instance of the column actually read, and declines on the mirrored condition for notEquals and notLike.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 10, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... label Sep 10, 2026
mapElementDefaultBreaksIndex evaluates the atom against a default-valued column, so a Set the
atom reads only has to be built. It required buildOrderedSetInplace to return a set with
explicit elements, which is the stronger property range analysis needs: Set::insertFromColumns
drops the stored elements once the set passes use_index_for_in_with_subqueries_max_values, and
FutureSetFromStorage returns null for an element-less set. The guard then declined, so a
map-element predicate whose subscript holds such an IN lost pruning that master performs:

    SELECT count() FROM tab_values
    WHERE m[if(0 IN (SELECT number FROM numbers(5)), 'abc', 'zzz')] = 'hello'
    SETTINGS use_index_for_in_with_subqueries_max_values = 1, force_data_skipping_indices = 'idx'

answers 1 on the merge base and raised INDEX_NOT_USED with the guard as published.
FutureSet::get() is exactly the precondition FunctionIn checks when the predicate runs
(src/Functions/in.cpp:149), so gate on that instead.

Reported by clickhouse-gh[bot] on ClickHouse#119336.
Comment on lines +553 to +559
auto future_set = column_set->getData();
if (!future_set)
return true;

future_set->buildOrderedSetInplace(context);
if (!future_set->get())
return true;

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.

This helper now trusts any ready ColumnSet, but the one-shot default-value evaluation is only safe for the same set shapes that MergeTreeIndexConditionText::prepareSetsForDefaultValueEvaluation accepts.

A ready FutureSetFromStorage from an ENGINE = Set table is still mutable during the query. In that shape, if('flip' IN s, 'abc', 'zzz') can fold here to one key, mapKeys pruning is planned for that key, and a concurrent INSERT into s can flip the runtime condition to the other key after the granule has already been pruned. The sibling text-index path declines mutable sets precisely to avoid that stale decision, and it also refuses prebuilt subquery sets when use_index_for_in_with_subqueries = 0.

Please reuse that helper here, or at least mirror its isMutableDuringQuery() and use_index_for_in_with_subqueries guards before trusting future_set->get().

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Neither symbol exists in the tree. prepareSetsForDefaultValueEvaluation and isMutableDuringQuery() have no hits under src/, and use_index_for_in_with_subqueries does not appear in MergeTreeIndexConditionText.cpp at all: its two sibling loops (:1756, :1853) call buildOrderedSetInplace and then test hasExplicitSetElements(), with no mutability guard. That setting is enforced one level down, in FutureSetFromSubquery::buildOrderedSetInplace, which returns null while it is 0, so a subquery set already declines here.

The premise is right, though. FutureSetFromStorage::buildOrderedSetInplace returns null for a StorageSet (nothing calls fillSetElements on its Set), so gating on readiness did admit sets the previous head declined: with a mapValues index over Map(String, String), m[if(m['q'] IN s, 'abc', 'zzz')] = 'hello' was INDEX_NOT_USED at 1e462d3 and uses the index at b3a5451.

The stale decision does not follow from it. Pruning here cannot read set contents: the evaluation substitutes the map's own default, and arrayElement(<empty map>, k) is the value default for every k, so no key the set selects changes the verdict; the mapKeys probe additionally needs a subscript that is already a materialized constant, and with a constant left side the IN folds before index analysis, leaving the plan filter reading m['abc'] = 'hello', so pruning and filtering share one literal. Measured: the index result equals use_skip_indexes = 0 for four shapes across three states of s, including inserting '' between runs, and the forced verdict never changed with s.

Probing it did find two real defects in that evaluation, both fixed in this push.

An error only the synthetic default raises used to fail the query. m[toString(intDiv(100, length(toString(m)) - 2))] = 'hello' answers 0 on master and raised ILLEGAL_DIVISION here, because only the substituted empty map makes the divisor zero. The set path fails the same way through the accurate cast FunctionIn applies: with ENGINE = Set over UInt64, m['q'] IN s raised CANNOT_PARSE_TEXT on the substituted '' while every stored value parses. An exception from the evaluation now declines the index, after asking the process list element whether the query is over its deadline, so a cancellation is not reported as an unusable index.

ActionsDAG::Node::isDeterministic reports only its own node, so a subscript containing sleep ran during index analysis: m[if(sleep(1) = 0, 'abc', 'zzz')] = 'hello' took 1.0s on master and 3.0s here, once per index built. Every function in the cloned expression must now be deterministic and suitable for constant folding.

One thing this does not fix, recorded in the description: a physical column named like a map subcolumn (m.key_x beside a map m) is read as that subcolumn, so mapKeys pruning can drop its rows. Master is wrong for m.key_x = 'hello' too and answered m.key_x = '' correctly only through the constant-typed default this PR removes; telling the two apart needs the column list this condition never receives.

@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 948c745cb8a1182839eee6cca6ea21d39493859f was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

The guard evaluates the predicate with the accessed map replaced by its type
default, so it hands the predicate's own functions an input no stored row
produces, and it runs them during index analysis. Two classes of query pay
for that.

An error only the synthetic input raises now fails the query. `WHERE
m[toString(intDiv(100, length(toString(m)) - 2))] = 'hello'` on
`Map(String, String)` answers 0 on master and fails with ILLEGAL_DIVISION
here: only the substituted empty map makes the divisor zero. A `Set` the
predicate reads fails the same way through the accurate cast `FunctionIn`
applies, so `m[if(m['q'] IN s, 'abc', 'zzz')]` against `ENGINE = Set` over
`UInt64` raises CANNOT_PARSE_TEXT while every stored value parses. An
exception from the evaluation therefore declines the index, as the helper
already does for any shape it cannot evaluate, and `KeyCondition`'s
`executeDeterministicDag` gives up on a constant transform the same way.
The catch covers the evaluation alone, and asks the process list element
whether the query is over its deadline before declining, so neither the
cancelled set build nor a function's own cancellation check is reported as
an index that could not be used.

A function that must not run during analysis ran anyway.
`ActionsDAG::Node::isDeterministic` reports only its own node, so the root
check passed a subscript containing `sleep`, which refuses constant folding
for exactly this reason: `WHERE m[if(sleep(1) = 0, 'abc', 'zzz')] = 'hello'`
took 1.0s on master and 3.0s here, once per index built. Every function in
the cloned expression is now required to be deterministic and suitable for
constant folding, checked before a Set is prepared for a shape that declines.

Both classes gain an arm. The first divides by a length only the empty map
makes zero, so it fails with ILLEGAL_DIVISION without this commit; the
second reads `sleep(0)` in the subscript, whose carrier stays usable without
the suitability check. The arm above the first keeps pinning that an error
the scan does raise still reaches the query.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1bbe0a7

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, distributed plan, s3 storage, parallel) / 03100_lwu_deletes_4_index trunk regression, not this diff: a lightweight-delete read step that reads zero columns now reports read_rows = 0. 38 distinct PRs and 3 true-master SHAs carry it since 2026-09-11T00:32Z #119400 (mine, open)
Upgrade check (amd_release) / Logical error: Got read request from replica A for unknown stream B. (STID: 5217-5b3d) parallel-replicas reading-coordinator abort on the previous-release binary the upgrade check loads, so no change to master can fix it there #119406 (mine, merged 2026-09-11T10:25:59Z, i.e. after this build). It is not in this head's gating set, so master gets merged on the next push to this branch rather than restarting CI for it now

Session id: cron:our-pr-ci-monitor:20260911-110100

ClickHouse#113157 landed on master and rewrote the same map branches of
traverseTreeEquals, so the two changes conflicted textually while staying
disjoint in purpose.

ClickHouse#113157 converts a constant into the index domain and threads
const_source_type through the map branches, then declines the index when a
map element is compared against the map value type default and the granule
is probed through a mapValues index. Its own commit message records that the
same shape on a mapKeys index stays wrong because the map value type is not
available there, which is what this branch fixes.

The resolution keeps both sides. const_source_type is still assigned on
every mapKeys substitution, so convertConstantToIndexDomain keeps converting
the substituted key, and reads_map_element_against_values_index is still set
on both mapValues arms, so the constantIsIndexDomainDefault guard keeps
firing. mapElementDefaultBreaksIndex replaces the two
unwrapped_value_type->getDefault() tests it supersedes, and the array needle
and text comparable key guards of this branch are unchanged.

Measured on the master snapshot that carries ClickHouse#113157 and not this branch, a
mapKeys index still drops matching rows: Map(String, String) with
tokenbf_v1 returns 1 against an oracle of 3, and Map(String, IPv6) with
ngrambf_v1 returns 0 against an oracle of 1.
The guard declined a mapKeys index whenever the indexed key type was not a
string, on the reasoning that the subcolumn probe searches for the key
serialized as text while the index holds the key column's raw bytes.

ClickHouse#113157 removed that premise. It sets const_source_type to String on the
subcolumn substitution and converts the constant into the index domain before
probing, so the serialized key text is turned back into the key's own
representation and does match. Keeping the guard therefore reverted that
improvement: 04716_text_index_ipv6_string_constant, which ClickHouse#113157 added,
failed with INDEX_NOT_USED on
`m.`key_2001:db8::abcd:1` = 'v'` over Map(IPv6, String).

Removing it does not reintroduce the over-prune this branch fixes, because
mapElementDefaultBreaksIndex still runs on both map branches and is what
declines a comparison the map element default satisfies. Measured on
Map(IPv6, Nullable(String)) with a mapKeys ngrambf_v1 index: an absent key
reads as NULL, `= ''` does not hold for NULL, and the indexed and unindexed
counts agree at 0, while the present key answers 1 either way.

05186's non-String key section asserted the old disposition, so it now states
what the two spellings really do: the subcolumn spelling uses the index, and
the arrayElement spelling still declines because it needs a String,
FixedString or Array key constant.
The literal pattern branch this PR adds tokenized the substituted key text
directly, while the equality branch converts it into the index domain first.
A map key whose type is not a string is held in the index as its own raw
bytes, so the text probe matched nothing and pruned the granule that holds
the key.

Measured on Map(IPv6, String) with a mapKeys ngrambf_v1 index and the row
map(toIPv6('2001:db8::abcd:1'), 'v'): `LIKE '%v%'` and `match(..., 'v')`
through the key subcolumn returned 0 against an oracle of 1, while `= 'v'`
returned 1. All three return 1 here, `LIKE '%zzz%'` still returns 0, the
index is still accepted under force_data_skipping_indices, and a two granule
table reports SelectedMarks 1 with the index against 2 without, so the probe
still prunes rather than declining.

Only reachable since the map merge dropped the guard that declined every
non-String key for this carrier, which ClickHouse#113157 had already made obsolete for
equality.
Converting the substituted key covers the atoms that probe the index for the
whole key. The remaining atoms tokenize their needle as a substring or a
token, which describes the key only while the index holds it as text, and
they read const_value after the map branches have replaced it with the
serialized key. On a key type that is not text they therefore probed text
against the key column's raw bytes and pruned the granule holding the key.

Measured on Map(IPv6, String) holding map(toIPv6('2001:db8::abcd:1'), 'vvv')
with a mapKeys ngrambf_v1 index: startsWith, endsWith and hasToken on the key
subcolumn returned 0 against an oracle of 1, as did has('') on a
Map(IPv6, Array(String)) holding ['']. The array needle guard does not cover
has, whose needle is a scalar, and the default guard does not either, because
an empty needle leaves the array default unmatched.

The guard sits before the hasToken and has branches rather than after the
equality ones, because both return early. It keeps every atom for a text key,
so a String keyed map prunes exactly as before, and it exempts the five atoms
that convert, so ClickHouse#113157's equality behaviour and this branch's literal
pattern probe are unchanged. A new atom defaults to declining, which costs
pruning and not correctness.
…`break`

The catch around the map element default evaluation exists so that analysis
raises nothing the scan would not: a function reading the map can throw on the
substituted default although no stored row reaches that input. It then asked
`QueryStatus::checkTimeLimit()` whether the query was killed or timed out, and
rethrew the caught exception when that returned false.

`checkTimeLimit()` returns false in exactly one state: `timeout_overflow_mode =
'break'`, a non-zero `max_execution_time` already elapsed, and the query not
killed. A kill and the 'throw' overflow mode both make it throw on its own
(`throwProperExceptionIfNeeded` in ProcessList.cpp, `handleOverflowMode` in
ExecutionSpeedLimits.cpp). So the bare `throw;` could fire only under 'break',
where it surfaced the probe's own incidental error:

    CREATE TABLE tab_ip (m Map(String, IPv6),
        INDEX idx mapKeys(m) TYPE ngrambf_v1(3, 512, 3, 0))
    ENGINE = MergeTree ORDER BY tuple();
    INSERT INTO tab_ip VALUES (map('abc', toIPv6('2001:db8:1:2:3:4:5:6')));
    SELECT count() FROM tab_ip
    WHERE m[if(intDiv(1, length(toString(m)) - 2) = 0, 'abc', 'zzz')]
          = '2001:db8:1:2:3:4:5:6'
    SETTINGS max_execution_time = 0.000001, timeout_overflow_mode = 'break';

returned `Code: 153 ILLEGAL_DIVISION`, raised by a division only the substituted
empty map performs, while the same query without the deadline answers 1 and the
same deadline with a predicate that does not throw returns cleanly. Whether the
query failed therefore depended on whether the probe happened to throw.

'break' asks for a partial result rather than an error, which is how the
execution path treats the same false return: LimitsCheckingTransform stops
reading and PipelineExecutor stops without an exception. Planning time polls
keep the call for its own throw and ignore the false (joinOrderDPSize,
joinOrderDPHyp, ReadFromTextIndexCount). Do that here too, so the index is
declined as it is for any other evaluation failure. The 'throw' overflow mode
still reports TIMEOUT_EXCEEDED, measured unchanged.
The parallel replicas stateless job enables parallel replicas in the default
profile, and the runner randomizes `parallel_replicas_local_plan`. With it at 0
the plan of `SELECT count() FROM tab_ip WHERE m['zzz'] = 'dead:beef::1'` is only
`ReadFromRemoteParallelReplicas`, with no local `ReadFromMergeTree`, so the
`Granules: 0/1` line the assertion looks for is absent and it returns 0.

Measured on a server with that job's profile and cluster, running the suite
with `--no-parallel-replicas` as the job does: 8 of 20 randomized runs failed on
this line, each with `parallel_replicas_local_plan = 0` and
`automatic_parallel_replicas_mode = 0`. With the pin, 30 of 30 pass, and 20 of
20 pass with parallel replicas off. A key the row has still shows no pruned
granule under the pin, so the assertion keeps its meaning.
groeneai and others added 2 commits October 10, 2026 12:42
…element-default-prune

Conflicts in MergeTreeIndexBloomFilterText.cpp, resolved against
ad41b84 (LowCardinality stripped from constants in
RPNBuilderTreeNode::tryGetConstant) and 27c8abd (RPNBuilderTreeContext
removed):

- The absent-key `const_value == value_type->getDefault()` guards that master
  rewrote stay replaced by mapElementDefaultBreaksIndex, which evaluates the
  predicate itself and so also covers the FixedString padding case master fixed
  there.
- The map-key constant no longer strips LowCardinality/Nullable by hand, as
  tryGetConstant already returns the value's own type.
- The query context comes from RPNBuilderTreeNode::getContext().
- Common/StringUtils.h is dropped with master's last use of it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…heck

`mapElementDefaultBreaksIndex` declined every predicate whose result type
was not `UInt8` after removing `Nullable`, so a `LowCardinality(UInt8)`
result such as `toLowCardinality(m['abc']) = 'hello'` lost the index. Master
now unwraps that lossless conversion to reach the map element, and uses the
index there, so this was a pruning regression of the branch against master.
The result is read with `getBool`, which handles both wrappers, as the same
gate in `MergeTreeIndexConditionText::traverseMapElementKeyNode` does.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 948c745

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 (arm_asan_ubsan, azure, sequential) job timeout, not a test failure: the job was stopped at its 9000 s limit after 1175 of 1180 tests, with no failed test. This job ended with the same error status on 109 PRs and 5 master runs in the last 24 hours #123849 (mine, open), which splits this job into 2 batches
Mergeable Check, PR praktika rollups of the row above #123849 (mine, open)

Session id: cron:our-pr-ci-monitor:20261010-180005

@clickhouse-gh clickhouse-gh Bot added comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. and removed comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... 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-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. groeneai-origin-self PR origin: self-found defect (impact-bar validated) 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