Skip to content

Fix JSONAllValues text index probe coercion - #113376

Closed
rorylshanks wants to merge 44 commits into
ClickHouse:masterfrom
rorylshanks:fix-json-all-values-text-coercion
Closed

rorylshanks wants to merge 44 commits into
ClickHouse:masterfrom
rorylshanks:fix-json-all-values-text-coercion

Conversation

@rorylshanks

@rorylshanks rorylshanks commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Related: #113022

Fix incorrect result filtering when a JSONAllValues text index serializes a comparison constant using a representation that differs from the JSON subcolumn. This includes value-changing coercions such as IPv4 to UInt32, types such as Bool whose semantic equality does not imply identical text, and DateTime representations that depend on time zones.

Equality and has predicates now use the index only when the probe representation is compatible with the statically typed JSON subcolumn or array element type. Equality and IN predicates on runtime-typed paths, casts from Dynamic paths, and values with session-dependent serialization are evaluated without this index.

Safe direct access and identity casts remain accelerated. Casts to String remain accelerated for statically typed values with stable serialization. Other value-changing casts decline index use because their stored representation cannot be inferred safely.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix incorrect results from JSONAllValues text indexes when comparison values require type coercion or have session-dependent or runtime types.


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

Coerce constants to the JSON subcolumn expression type before serializing text index probes. Keep identity and `String` casts accelerated, and decline value-changing casts whose stored representation cannot be inferred safely.
@CurtizJ CurtizJ added the can be tested Allows running workflows for external contributors label Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6bc9c6c]

Summary: ✅


AI Review

Summary

This PR narrows JSONAllValues text-index use for typed JSON subcolumns and adds broad regression coverage for coercion, stable stringification, and Variant/Dynamic edge cases. One correctness gap still remains: the raw-node matcher still treats wrapped Variant carriers as non-Variant, so helper-driven string predicates can still prune away the row-level ILLEGAL_TYPE_OF_ARGUMENT exception that the bare-Variant fixes were meant to preserve.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:1094] The raw JSONAllValues matcher checks !isVariant(node_dag->result_type) before stripping Nullable / LowCardinality, unlike the fixed cast path a few lines above. That reopens the original Variant contract for wrapped carriers such as JSON(v Nullable(Variant(UInt64, String))): match(data.v, 'zzz'), like(data.v, '%z%'), hasToken(data.v, 'zzz'), and similar helpers can still route through the text index, tokenize the probe, and skip the granule instead of surfacing the row-level ILLEGAL_TYPE_OF_ARGUMENT from FunctionVariantAdaptor. Strip wrappers before the isVariant check, or otherwise reject raw wrapped-Variant carriers here, so the raw matcher matches the already-fixed cast branch.
Tests
  • ⚠️ Add a focused stateless regression for a raw wrapped-Variant path, for example JSON(v Nullable(Variant(UInt64, String))) or JSON(v LowCardinality(Variant(UInt64, String))), and assert that match(data.v, 'zzz') raises the same ILLEGAL_TYPE_OF_ARGUMENT with skip indexes both enabled and disabled. The current suite covers bare Variant and CAST(... AS Variant(...)), but not the wrapped carrier that still passes line 1094.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: reject raw wrapped-Variant carriers in matchesNodeToJSONAllValuesIndex, and add a focused regression proving skip indexes do not suppress the Variant type-mismatch exception for those wrappers.

LLVM Coverage Report

Measured on commit 6bc9c6c.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 81.40% 81.30% -0.10%

Changed lines: Changed C/C++ lines covered: 122/132 (92.42%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 4, 2026
Keep typed-path defaults indexed because `JSONAllValues` materializes them, add `String`-cast default coverage, and avoid plan expectations for declined non-identity casts.

Related: ClickHouse#113376
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 5, 2026
Remove unsupported `Array(String)` cast cases instead of bypassing `EXPLAIN`.

Related: ClickHouse#113376
@rorylshanks

Copy link
Copy Markdown
Contributor Author

Hey @CurtizJ it looks like this one has been applied with a "manual approve" label. Is it because I modified an older test?
I think the previous test assertions are not valid with some of these improvements bypassed due to correctness issues.

@CurtizJ

CurtizJ commented Aug 5, 2026

Copy link
Copy Markdown
Member

it looks like this one has been applied with a "manual approve" label

I think it's a bug.

@CurtizJ CurtizJ removed the manual approve Manual approve required to run CI label Aug 5, 2026
Propagate source types through `Tuple` and `Map` constants so nested values are serialized with the stored JSON types. Cover direct and array composite comparisons.

Related: ClickHouse#113376
Compare the dynamic `data.id` string path with a string literal so the query remains valid while preserving the optimizer assertion.

Related: ClickHouse#113376
@rorylshanks

Copy link
Copy Markdown
Contributor Author

Populate the new typed composite paths in every granule so their defaults do not add unrelated tokens to existing pruning assertions.

Related: ClickHouse#113376
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 6, 2026
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator

The job you linked failed on 04648_geohashes_in_box_cancellation, which is not in your diff. It is the only [ FAIL ] in that job, and 04062_text_index_json_all_values_ghdata was [ SKIPPED ] there with Reason: object-storage, so nothing your change touches ran in that job at all.

That test is mine (shipped by 112273). The failure is a wall-clock promptness overshoot on the assertions 112823 kept:

-float64 throw stopped promptly
+float64 throw ran 5355ms past a 1000ms limit

The job's own diagnostics re-ran it and reported Failed 0 out of 3 reruns. Measured on the post-112823 file (check_start_time > '2026-08-02 00:00:00'): 4 FAIL / 12125 OK across 4 distinct pull requests, and on master 0 FAIL / 894 OK. So it is a low-rate timing flake unrelated to your branch, it is mine, and no fixing pull request exists for it yet. A fix task is created and the overshoot is being investigated at full effort; I will post the fixing pull request link in this thread when it opens.

The other four Stateless failures on that same head are a different test, and those do come from your diff. 04062_text_index_json_all_values_ghdata fails on amd_asan_ubsan, distributed plan, amd_debug, amd_tsan and arm_binary with:

Code: 386. DB::Exception: There is no supertype for types String, UInt64 because some of them are String/FixedString/Enum and some of them are not
(in query: SELECT length(JSONAllPaths(data)), cityHash64(JSONAllPaths(data)), length(JSONAllValues(data)), cityHash64(JSONAllValues(data)) FROM ghdata WHERE data.id = 14690746673)

Commit 88db1c5 replaced master's data.id::UInt64 = 14690746673 with the bare-integer data.id = 14690746673. On unmodified master, on a table with no text index at all, the bare-integer form throws that same 386, while both data.id = '14690746673' and data.id::UInt64 = 14690746673 return the row. So it is about comparing that JSON subcolumn (toTypeName(data.id) is Dynamic, holding a String here) against an integer literal, and is independent of the text index. Breadth agrees it is specific to this branch: over the last 14 days that test has 21 FAIL rows across 3 pull requests and 0 on master (0 FAIL / 1962 OK), and the NO_COMMON_TYPE signature appears only in this pull request's rows.

Your newest commit 234c70e already changes both occurrences to data.id = '14690746673', which returns the row on master, so that half should be resolved on head 22c5a7a. Its CI is currently sitting in the workflow approval gate (action_required, no check runs recorded yet), so there is no result to read from it.

@CurtizJ CurtizJ self-assigned this Aug 7, 2026
rorylshanks added a commit to rorylshanks/ClickHouse that referenced this pull request Aug 7, 2026
Allow `JSONAllValues` Bloom-filter conditions to evaluate supported
predicates on an explicit `String` cast while keeping direct `Dynamic`
and `Variant` comparisons disabled.

Declared JSON defaults are already emitted by `JSONAllValues`, so keep
those concrete typed predicates indexable and only guard missing
`Dynamic` and `Variant` string defaults.

Related: ClickHouse#113022
Related: ClickHouse#113376
rorylshanks added a commit to rorylshanks/ClickHouse that referenced this pull request Aug 7, 2026
Keep JSON `IN` handling on scalar paths instead of extending the existing
tuple set mapping. Collapse the unused direct and identity-cast states and
centralize value conversion and serialization.

Remove duplicate assertions and use timezone-independent `Dynamic` values
for the explicit `String` predicate coverage.

Related: ClickHouse#113022
Related: ClickHouse#113376
Decline the index when the comparison value type differs from the JSON subcolumn type instead of recursively coercing constants. Keep focused coverage and preserve the existing query cases.

Related: ClickHouse#113376
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6bc9c6cb6 with master 3476b12ea (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.

Object file sizes

3 object files changed (+29.98 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexConditionText.cpp.o 836.93 KiB 866.93 KiB +30.00 KiB (+3.58%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

`Time64` text serialization is independent of session time zones and format settings. Allow direct and string-cast probes to retain text-index pruning, with focused coverage.
@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 4, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator

Closing the loop on my earlier comment here. I said I would post the fixing pull request link for 04648_geohashes_in_box_cancellation once it opened. There is no fix pull request, so here is the resolution instead: the test was removed from master in #114061 (merged 2026-08-10).

I wrote that test and I agreed with removing it. Its promptness assertions measure the wall-clock latency of an in-loop cancellation checkpoint, and I could not find an oracle for that property which is sound from a stateless test. The details are in #112273 (comment).

Nothing is needed on your side. Your current head b13f526 no longer carries the file, and the test has 0 FAIL in 740 CIDB rows since the deletion, so that failure cannot recur on this pull request.

@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Dear @CurtizJ, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

Keep the date/time type headers needed for representation-safe probes
and use the current text-index includes and map-shadowing checks.

The outstanding review proposes wrapped `Variant` carriers that cannot
be constructed: `DataTypeVariant::canBeInsideNullable` returns false,
and its inherited `canBeInsideLowCardinality` also returns false.
Both proposed JSON table definitions return `ILLEGAL_TYPE_OF_ARGUMENT`
before index matching. No unreachable unwrapping path is added.

Validation: changed-source compile and C++ style checks.
Runtime validation of the merged sources remains with CI.

ClickHouse#113376
Reject identity casts to `Variant` in the shared `JSONAllValues` index matcher so pruning cannot suppress predicate type errors. Add a regression for both index-reading modes and preserve explicit `String` cast acceleration.

Related: ClickHouse#113376 (comment)

Related: ClickHouse#113376
@rorylshanks

Copy link
Copy Markdown
Contributor Author

Closing this. Each edge case I fixed exposed another representation mismatch, and the guard kept narrowing the index. Comparing the literal's text against value tokens can't be made exact once types coerce.

The simple and safe fix for #119593 is to decline the index for =/IN on Dynamic paths, like minmax and bloom_filter do. I'd rather put effort into indexes that store the type (#114613, #113022).

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-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... manual approve Manual approve required to run CI pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants