Skip to content

Unwrap toString() when matching JSON subcolumns to JSONAllPaths/JSONAllValues text indexes - #133245

Open
yackushevas wants to merge 7 commits into
ClickHouse:masterfrom
yackushevas:anton-tostring-json-text-index
Open

yackushevas wants to merge 7 commits into
ClickHouse:masterfrom
yackushevas:anton-tostring-json-text-index

Conversation

@yackushevas

@yackushevas yackushevas commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

A text index over JSONAllPaths(json)/JSONAllValues(json) is not used when the filter wraps the subcolumn into toString():

WHERE json.host = 'value'                 -- index pruning (works)
WHERE CAST(json.host AS String) = 'value' -- index pruning (works)
WHERE toString(json.host) = 'value'       -- full scan (fixed by this PR)

toString() renders the value's text representation — the same one JSONAllValues stores — so unwrapping it is equivalent to the already-supported CAST(x, 'String') unwrapping. Only the 1-argument form is unwrapped; downstream safety checks (shadowing subcolumns, typed paths, ^/@ prefixes) are unchanged.

Render-safe pruning

The index stores the value as rendered at the declared default format settings — neither the INSERT session nor the server profile changes that — while toString()/CAST(..., 'String') render with the session's effective settings. Where the predicate does not compare the stored text, pruning silently drops matching rows, also through the pre-existing CAST(...) form:

CREATE TABLE t (id UInt32, data JSON(ts DateTime64(6,'UTC'), b Bool, fa Array(Float64), fs FixedString(3), x Nullable(UInt8)),
    INDEX vals JSONAllValues(data) TYPE text(tokenizer = 'array'))
    ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 1;
INSERT INTO t VALUES (1, '{"ts": "2024-01-01 00:00:00.123000", "b": true, "fa": [1.5, 0.25], "fs": "a", "x": 1}'), (2, '{}');

SELECT count() FROM t WHERE CAST(data.ts, 'String') = '2024-01-01 00:00:00.123'
    SETTINGS date_time_64_output_format_cut_trailing_zeros_align_to_groups_of_thousands = 1;  -- 0 instead of 1
SELECT count() FROM t WHERE toString(data.b) = 'YES' SETTINGS bool_true_representation = 'YES';  -- 0 instead of 1
SELECT count() FROM t WHERE toString(data.fa) = '[1.5,0.3]' SETTINGS output_format_float_precision = 1;  -- 0 instead of 1
SELECT count() FROM t WHERE toString(data.fs) = 'a';  -- 0 instead of 1, at default settings
SELECT count() FROM t WHERE CAST(data.b, 'Int8') = 1;  -- 0 instead of 1: compares the value, not its text
SELECT count() FROM t WHERE CAST(data.x, 'String') = '1';  -- 1, while use_skip_indexes = 0 raises: the cast of a missing value fails

Conversion-wrapped predicates therefore decline JSONAllValues pruning when:

  • a format setting differs from its declared default: hasNonDefaultFormatSettings() over FORMAT_FACTORY_SETTINGS, including the values inherited from the server profile. The earlier list of "rendering" settings did not hold — an exhaustive pass over every format setting found output_format_float_precision (rendering of Array(Float64)) on top of the Bool and DateTime64 ones;
  • the typed path is FixedString(N), also under LowCardinality/Nullable: the rendering drops the trailing zero bytes that JSONAllValues keeps, at any settings. Dynamic paths never hold FixedString (stored as String); Array/Map with FixedString inside render consistently;
  • the cast is to a type other than String: it compares the value, which the index does not store (pre-existing for CAST);
  • the typed path is Nullable and the conversion's result is not: CAST(path, 'String') is typed as String, so a missing or NULL value fails at row level, and pruning the granule — the index stores a token for the NULL — would turn that failure into a result (pre-existing for CAST). toString() keeps NULL and is still pruned.

The predicate falls back to a scan. Plain subcolumn predicates keep the index: their literal is compared as written. The remaining divergence — a literal matching row-level through type coercion — predates this PR and is tracked in #119593.

Checked as index path vs use_skip_indexes = 0, no differences: 28 typed path types × 2 tokenizers × 4 predicate forms (224 queries); every format setting moved off its default, 331 settings × 9 types × toString =/CAST =/LIKE (8937 queries); a 900-query equivalence matrix on 2K-row tables (dynamic and typed paths, 4 settings states, 20 predicate shapes); and a server whose default profile changes four format settings (pruning declined in a fresh session, allowed once the session resets them to the declared defaults).

Benchmark (20M rows, JSON column, default settings, condition cache off, cold page cache; A/B binaries, identical data):

query read_rows before read before read_rows after read after
data.host = 'needle' (control) 16 384 152 KiB 16 384 152 KiB
toString(data.host) = 'needle' 20 000 000 398 MiB 16 384 152 KiB

The control form is unaffected; the wrapped form becomes identical to it (×1220 fewer rows read). Results are unchanged (index path == brute force, also verified on production data).

Tests: 05838_tostring_json_text_index — results and EXPLAIN index conditions for the wrapped forms at default settings (index used); no pruning (results == brute force) for the FixedString path, under the settings above, for a cast to a non-String type, and for a cast of a Nullable path to String (EXPLAIN only: the cast of a missing value raises). The EXPLAIN assertions select only the lines of the index analysis, so the test does not depend on the plan shape; the CAST lines fail on master. Neighbouring suites pass: 04058, 02346_text_index_function_like, 02346_text_index_map_support, 02346_text_index_on_subcolumns, 05198_json_skip_index_typed_path_subcolumn.

Changelog category (leave one):

  • Performance Improvement

Changelog entry:

Text indexes over JSON columns: use the index for toString()-wrapped subcolumn filters; stop pruning CAST/toString-wrapped predicates when a format setting is not at its default, the path is a typed FixedString, or the cast compares something other than the stored text, which could drop rows or hide an error.


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

`tryMatchNodeToJSONIndex` unwrapped only `CAST`/`_CAST` around a JSON subcolumn, so a filter
like `toString(json.path) = 'value'` lost the index and fell back to a full scan, while
`json.path = 'value'` and `CAST(json.path, 'String') = 'value'` pruned fine.
`toString()` renders the value's text representation - the same representation
`JSONAllValues` stores (string values as-is, other types as text) - so unwrapping it is
semantically equivalent to the already-supported cast unwrapping. Only the 1-argument form
is unwrapped; downstream safety checks (shadowing subcolumns, typed paths, `^`/`@` prefixes)
are unchanged.

Benchmark (20M rows, JSONAllValues text index, cold page cache, condition cache off):
`toString(data.host) = 'needle'` reads 20,000,000 rows / 398 MiB before, 16,384 rows /
152 KiB after - identical to the unwrapped form; the unwrapped form is unaffected.
@yackushevas
yackushevas force-pushed the anton-tostring-json-text-index branch from 2ba27b2 to 4c1cfbd Compare November 20, 2026 15:03
@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 Nov 20, 2026
@shihchengwei-lab

Copy link
Copy Markdown

For a JSON path declared as ts DateTime64(6, 'UTC'), enabling date_time_64_output_format_cut_trailing_zeros_align_to_groups_of_thousands lets toString(j.ts) render .123000 as .123. JSONAllValues(j) appears to keep .123000 when building the index. I traced the formatting paths but haven’t run this case on the PR build.

With splitByNonAlpha, what prevents the index from skipping a granule whose only row matches toString(j.ts) = '2024-01-01 00:00:00.123', given that the indexed token would be 123000 and the query token 123?

@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Nov 21, 2026
…N path predicates when text-rendering settings are not default

`toString(json.path)` and `CAST(json.path, 'String')` render values with the session's
text-rendering format settings, while a `JSONAllValues` text index stores the default
rendering (built at INSERT time with default settings). When a setting such as
`date_time_64_output_format_cut_trailing_zeros_align_to_groups_of_thousands` or
`bool_true_representation` changes the rendering, the query tokens diverge from the
indexed tokens and pruning silently drops granules with matching rows:

    CREATE TABLE t (id UInt32, data JSON(ts DateTime64(6,'UTC')),
        INDEX vals JSONAllValues(data) TYPE text(tokenizer = splitByNonAlpha))
        ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 1;
    INSERT INTO t VALUES (1, '{"ts": "2024-01-01 00:00:00.123000"}');

    SELECT count() FROM t WHERE CAST(data.ts, 'String') = '2024-01-01 00:00:00.123'
        SETTINGS date_time_64_output_format_cut_trailing_zeros_align_to_groups_of_thousands = 1;
    -- 0 (wrong; the rendered '.123' does not match the indexed token '123000')
    -- the same query with use_skip_indexes = 0 returns 1

The same holds for `toString(...)` with this patch's unwrapping. Decline the pruning
when such a predicate goes through a string conversion of the JSON path and a
text-rendering setting is not at its default; the predicate falls back to a scan and
returns correct results. Plain subcolumn predicates keep the index: they compare the
literal text as written and are unaffected by rendering settings.
@yackushevas

Copy link
Copy Markdown
Contributor Author

Thanks @shihchengwei-lab — confirmed and fixed. Under the setting, toString(j.ts) renders .123 while the index stores .123000, so the wrapped predicate would prune the matching granule. The same happens on master for the already-supported CAST(j.ts,'String') — checked before this change.

570502b declines JSONAllValues pruning for conversion-wrapped (CAST/toString) JSON path predicates when a text-rendering setting (date_time_64_output_format_cut_trailing_zeros_align_to_groups_of_thousands, bool_true_representation, bool_false_representation) is not at its default; the predicate falls back to a scan and returns correct results. Plain predicates keep the index — their literal is compared as written. The index keeps the default rendering regardless of the INSERT-time session (verified).

The remaining divergence — a literal matching row-level through type coercion — predates this PR and is tracked in #119593.

Covered in 05838_tostring_json_text_index: DateTime64 path under the setting → no pruning, results == brute force; same for a custom bool_true_representation; at default settings the wrapped form still uses the index.

`getFormatSettings()` was built for every function node of a predicate, even when
no JSON subcolumn index is involved; check the node kind first. Also take
`getFunctionName()` by value like the neighbouring code. No behavior change.
…-text-index

Resolve the conflict in tryPrepareSetForTextSearch: keep the new has_index_for_argument
tracking, and decline JSONAllValues for a string conversion of a JSON path under
non-default text-rendering settings. Update one EXPLAIN line of the reference for the
nullIf(hint, 0) wrapping of Nullable predicates.
@george-larionov george-larionov added the can be tested Allows running workflows for external contributors label Dec 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c8ce89b]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) FAIL
04099_text_index_json_all_values_array FAIL cidb
04061_text_index_json_all_values FAIL cidb
02346_text_index_hasPhrase_array_phrase_json FAIL cidb
04061_text_index_json_all_values_ngrams FAIL cidb
04099_text_index_json_all_values_array FAIL cidb
Too many test failures FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

This PR enables text-index pruning for toString-wrapped JSON subcolumns and adds conversion-safety guards. Block: comparison with the PR binary and master reproduced three new wrong-result paths and two remaining variants of the nullable-cast defect. There are four blocker findings below; the two new findings were posted in one batched review, and incomplete fixes were addressed on their existing threads.

Findings

❌ Blockers

  • Link to the thread src/Storages/MergeTree/MergeTreeIndexJSONSubcolumnHelper.cpp:198 Filtering a missing array subcolumn through toString loses matching rows with JSONAllValues text indexes and JSONAllPaths bloom indexes.

    • Repro:
      CREATE TABLE t
      (
          id UInt8,
          data JSON,
          INDEX vals JSONAllValues(data) TYPE text(tokenizer = 'array')
      ) ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 1;
      INSERT INTO t VALUES (1, '{}');
      
      SELECT count() FROM t WHERE toString(data.x.:`Array(Int64)`) = '[]';
      -- 0 on this PR; 1 on master
      SELECT count() FROM t WHERE toString(data.x.:`Array(Int64)`) = '[]'
      SETTINGS use_skip_indexes = 0;
      -- 1
    • Evidence: ✅ Reproduced with Fast test of c8ce89b5, compared with Build (arm_release) of master 0dcf7388.
    • Cause: A missing type-specific array subcolumn reads as [], which becomes the nonempty string '[]', although the index contains neither the path nor its value. The new matching enables pruning without checking this converted default. getTypedPathType supplies no declared type for a dynamic path. IN ('[]') also returns 0 instead of 1. Replacing the index with JSONAllPaths(data) TYPE bloom_filter or TYPE tokenbf_v1(1024, 3, 0) reproduces the same new regression: those callers check the default of the converted String rather than the converted source default. All these toString queries return 1 on master.
  • Link to the thread src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:1403 Filtering an array’s size0 subcolumn through toString loses matching rows even when the path and array are present.

    • Repro:
      CREATE TABLE t
      (
          id UInt8,
          data JSON,
          INDEX vals JSONAllValues(data) TYPE text(tokenizer = 'array')
      ) ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 1;
      INSERT INTO t VALUES (1, '{"x":[1,2]}');
      
      SELECT count() FROM t
      WHERE toString(data.x.:`Array(Nullable(Int64))`.size0) = '2';
      -- 0 on this PR; 1 on master
      SELECT count() FROM t
      WHERE toString(data.x.:`Array(Nullable(Int64))`.size0) = '2'
      SETTINGS use_skip_indexes = 0;
      -- 1
    • Evidence: ✅ Reproduced with Fast test of c8ce89b5, compared with Build (arm_release) of master 0dcf7388.
    • Cause: extractPathFromSubcolumn discards the type selector and everything after it, including .size0, so the expression is matched to path x. The safety gate accepts this dynamic path even though the predicate compares its array length, '2', while the index stores the array text, '[1,2]'. The array tokenizer prunes the matching granule. The same query returns 1 on master, independently of the missing-path defect above.
  • Link to the thread src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:1226 A FixedString value inside a Variant still loses matching rows, leaving the earlier render-safety fix incomplete.

    • Repro:
      CREATE TABLE t
      (
          id UInt8,
          data JSON(x Variant(FixedString(3), UInt64)),
          INDEX vals JSONAllValues(data) TYPE text(tokenizer = 'array')
      ) ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 1;
      INSERT INTO t VALUES (1, '{"x":"a"}');
      
      SELECT count() FROM t WHERE toString(data.x) = 'a';
      -- 0
      SELECT count() FROM t WHERE toString(data.x) = 'a'
      SETTINGS use_skip_indexes = 0;
      -- 1
    • Evidence: ✅ Reproduced with Fast test of c8ce89b5, compared with Build (arm_release) of master 0dcf7388.
    • Cause: The guard removes LowCardinality and Nullable but accepts an outer Variant. Conversion dispatches to the active FixedString, producing hex 61; the index serializer retains 610000. Master returns 1 for both toString queries. The equivalent CAST predicate is already wrong on master and belongs to the rendering discrepancy this PR explicitly claims to fix. The bot-owned thread was reopened, with one reply demonstrating why the author's fixed claim does not cover the current code.
  • Link to the thread src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:1208 The nullable-cast fix still lets index pruning replace a row-level conversion exception with a successful result.

    • Repro:
      CREATE TABLE t
      (
          id UInt8,
          data JSON(x Nullable(UInt8)),
          INDEX vals JSONAllValues(data) TYPE text(tokenizer = 'array')
      ) ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 1;
      INSERT INTO t VALUES (1, '{}');
      
      SELECT count() FROM t WHERE toNullable(CAST(data.x, 'String')) = '1';
      -- 0
      SELECT count() FROM t WHERE toNullable(CAST(data.x, 'String')) = '1'
      SETTINGS use_skip_indexes = 0;
      -- CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN
    • Evidence: ✅ Reproduced with Fast test of c8ce89b5, compared with Build (arm_release) of master 0dcf7388.
    • Cause: The guard checks the outer argument’s result nullability, so toNullable bypasses it even though the inner CAST still throws. It also checks only declared path nullability: with data Nullable(JSON(x UInt8)) and a NULL parent, data.x is actually Nullable(UInt8), while getTypedPathType reports UInt8. Plain CAST(data.x, 'String') = '1' then returns 0 indexed and throws without the index. Both variants reproduce on master and remain in scope because the PR explicitly claims to prevent nullable conversions from hiding exceptions. One reply was added to the existing thread with the current-code counterexamples.
Pre-existing issues
Final Verdict

Status: ❌ Block

Preserve indexed/scan equivalence for missing array defaults, array subcolumns, FixedString alternatives in Variant, and nullable casts through wrappers or nullable parent columns, with focused regression coverage.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Dec 1, 2026
const auto format_settings = getFormatSettings(context);
return !format_settings.date_time_64_output_format_cut_trailing_zeros_align_to_groups_of_thousands
&& format_settings.bool_true_representation == "true"
&& format_settings.bool_false_representation == "false";

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.

[Blocker] output_format_trim_fixed_string is another text-rendering setting that this default-check misses. SerializationFixedString::serializeText trims trailing NULs when that setting is 1, so the render-safety hole remains for CAST(data.fs, 'String') = 'a', and this patch extends the same wrong-answer path to toString(data.fs) = 'a': with data JSON(fs FixedString(3)), INDEX vals JSONAllValues(data) TYPE text(tokenizer = splitByString(['|'])), and SET output_format_trim_fixed_string = 1, the indexed query returns [] while ... SETTINGS use_skip_indexes = 0 returns [1]. The index still stores 61 00 00, but the wrapped predicate renders 61, so the granule gets pruned away.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in fe10621. The cause is narrower than the setting: toString() and CAST(FixedString AS String) drop the trailing zero bytes that JSONAllValues keeps, at any settings (output_format_trim_fixed_string takes no part: neither conversion consults it, and the index is built at the declared default settings). Conversion-wrapped predicates now also decline pruning for a typed FixedString path, including LowCardinality/Nullable wrappers.

While verifying, an exhaustive pass over all format settings found a second hole in the settings list (output_format_float_precision changes the rendering of Array(Float64)), so the list is replaced by a structural gate: decline when any format setting differs from its declared default (hasNonDefaultFormatSettings). Both cases are in 05838_tostring_json_text_index.

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.

[Blocker] The fix in fe106211314e still misses a FixedString carried by a Variant. In the current code, src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:1226 checks only the outer type after removing LowCardinality/Nullable; it accepts Variant(FixedString(3), UInt64) even though the same trailing-zero mismatch remains.

  • Repro:
CREATE TABLE t
(
    id UInt8,
    data JSON(x Variant(FixedString(3), UInt64)),
    INDEX vals JSONAllValues(data) TYPE text(tokenizer = 'array')
) ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 1;
INSERT INTO t VALUES (1, '{"x":"a"}');

SELECT count() FROM t WHERE toString(data.x) = 'a';
-- 0
SELECT count() FROM t WHERE toString(data.x) = 'a'
SETTINGS use_skip_indexes = 0;
-- 1
  • Evidence: ✅ Reproduced with Fast test of c8ce89b5, compared with Build (arm_release) of master 0dcf7388.
  • Cause: toString dispatches to the active variant and renders hex 61, while the index serializer keeps 610000. Master returns 1 for both toString queries; the equivalent CAST(data.x, 'String') already returns the wrong indexed result on master, so the claimed render-safety fix remains incomplete as well.

@clickhouse-gh

clickhouse-gh Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fe1062113 with master 8da18dcb5 (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

5 object files changed (+188.40 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Formats/FormatFactory.cpp.o 1.64 MiB 1.82 MiB +183.62 KiB (+10.92%)

729 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

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

Job report

The "targeted" and "flaky check" jobs run tests with random settings, which moves the
filter out of PREWHERE and changes the nesting of the plan in EXPLAIN. The EXPLAIN
assertions now select only the lines of the index analysis, which do not depend on
the plan shape.
…are the stored text

toString() and CAST(... AS String) render a value with the session's effective
format settings, while a JSONAllValues index stores it as rendered at the declared
defaults. An exhaustive check over every format setting found output_format_float_precision
changing the rendering of Array(Float64) on top of the listed Bool and DateTime64
settings, so the list is replaced by a check over all format settings.

A typed FixedString path diverges at any settings: the rendering drops the trailing
zero bytes that JSONAllValues keeps. A cast to a type other than String compares the
value, not its text. Both affected the CAST form before this PR.
return true;
if (!isStringConversionOfJSONPath(node))
return false;
return !hasNonDefaultFormatSettings(context->getSettingsRef()) && !isTypedFixedStringPath(json_info, json_argument_types);

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.

[Blocker] CAST(..., 'String') on a typed Nullable(...) JSON path is still not safe to prune here. On a missing path, row execution raises CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN, but JSONAllValues stores a token for that NULL and this guard still treats the wrapped predicate as indexable, so the skip index can drop the whole granule and turn the exception into a result.

  • Repro:
CREATE TABLE t
(
    id UInt8,
    data JSON(x Nullable(UInt8)),
    INDEX vals JSONAllValues(data) TYPE text(tokenizer = 'array')
) ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 1;
INSERT INTO t VALUES (1, '{}');

SELECT count() FROM t WHERE CAST(data.x, 'String') = '1';
-- 0
SELECT count() FROM t WHERE CAST(data.x, 'String') = '1' SETTINGS use_skip_indexes = 0;
-- exception `CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN`
  • Evidence: ✅ Reproduced with ci/tmp/review_133245_bin/clickhouse local review.
  • Cause: conversionOfJSONPathIsSafeToPrune only rejects non-default format settings and typed FixedString paths. It does not account for conversion-wrapped predicates whose row-level evaluation can fail on missing / NULL JSON typed paths, so the indexed plan is not semantically equivalent to the brute-force one.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in c8ce89b. CAST(path, 'String') of a typed Nullable path is typed as String, so a missing or NULL value fails at row level while the index stores a token for the NULL. The gate now declines pruning whenever a typed Nullable path is converted to a non-nullable type; toString() keeps NULL and is still pruned. Covered by index condition: Nullable path, CAST-wrapped (no pruning) in 05838_tostring_json_text_index (EXPLAIN only, as the cast of a missing value raises). Pre-existing for CAST on master.

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.

[Blocker] The fix in c8ce89b59371 still allows the original exception-hiding behavior through a wrapper. src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:1208-1212 checks the outer argument's result type, so toNullable makes the check pass even though its inner CAST still throws.

  • Repro:
CREATE TABLE t
(
    id UInt8,
    data JSON(x Nullable(UInt8)),
    INDEX vals JSONAllValues(data) TYPE text(tokenizer = 'array')
) ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 1;
INSERT INTO t VALUES (1, '{}');

SELECT count() FROM t WHERE toNullable(CAST(data.x, 'String')) = '1';
-- 0
SELECT count() FROM t WHERE toNullable(CAST(data.x, 'String')) = '1'
SETTINGS use_skip_indexes = 0;
-- CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN
  • Evidence: ✅ Reproduced with Fast test of c8ce89b5, compared with Build (arm_release) of master 0dcf7388.
  • Cause: The outer expression is nullable, but evaluating its inner cast is still invalid on NULL. A second producer bypasses the same guard: with data Nullable(JSON(x UInt8)) and a NULL parent, data.x is actually Nullable(UInt8) while getTypedPathType returns the declared UInt8; plain CAST(data.x, 'String') = '1' again returns 0 indexed and throws on a scan. Both variants also reproduce on master and remain within the nullable-cast behavior this fix claims to address.

… non-nullable type

CAST(path, 'String') of a typed Nullable path is typed as String, so a missing or NULL
value fails at row level. The index stores a token for the NULL and pruned the granule,
turning the failure into a result. toString() keeps NULL and is still pruned.
if ((fname == "CAST" || fname == "_CAST") && func.getArgumentsSize() == 2)
json_info = tryMatchJSONSubcolumnToIndex(
func.getArgumentAt(0).getColumnName(), index_columns, json_function_name, json_argument_types, is_shadowing_subcolumn);
else if (fname == "toString" && func.getArgumentsSize() == 1)

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.

[Blocker] Filtering a missing type-specific array subcolumn through toString now silently drops matching rows, including with JSONAllPaths bloom indexes.

  • Repro:
CREATE TABLE t
(
    id UInt8,
    data JSON,
    INDEX vals JSONAllValues(data) TYPE text(tokenizer = 'array')
) ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 1;
INSERT INTO t VALUES (1, '{}');

SELECT count() FROM t WHERE toString(data.x.:`Array(Int64)`) = '[]';
-- 0 on this PR; 1 on master
SELECT count() FROM t WHERE toString(data.x.:`Array(Int64)`) = '[]'
SETTINGS use_skip_indexes = 0;
-- 1
  • Evidence: ✅ Reproduced with Fast test of c8ce89b5, compared with Build (arm_release) of master 0dcf7388.
  • Cause: A missing array subcolumn reads as [], so its converted default is '[]', although neither the path nor a value is present in the index. The new unwrapping enables pruning without accounting for that converted default. getTypedPathType returns no declared type for this dynamic path, so the values-index gate permits it. IN ('[]') also loses the row. Replacing the index declaration with INDEX paths JSONAllPaths(data) TYPE bloom_filter or TYPE tokenbf_v1(1024, 3, 0) reproduces the same regression: those callers test the default of the converted String ('') rather than the source array's converted default.

else if (tryMatchNodeToJSONIndex(index_column_node, header, "JSONAllValues", json_argument_types))
else if (auto json_info = tryMatchNodeToJSONIndex(index_column_node, header, "JSONAllValues", json_argument_types))
{
if (!conversionOfJSONPathIsSafeToPrune(argument_node, index_column_node, *json_info, json_argument_types, getContext()))

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.

[Blocker] toString predicates on an array's size0 subcolumn now lose matching rows because the values index stores the array, not its length.

  • Repro:
CREATE TABLE t
(
    id UInt8,
    data JSON,
    INDEX vals JSONAllValues(data) TYPE text(tokenizer = 'array')
) ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 1;
INSERT INTO t VALUES (1, '{"x":[1,2]}');

SELECT count() FROM t
WHERE toString(data.x.:`Array(Nullable(Int64))`.size0) = '2';
-- 0 on this PR; 1 on master
SELECT count() FROM t
WHERE toString(data.x.:`Array(Nullable(Int64))`.size0) = '2'
SETTINGS use_skip_indexes = 0;
-- 1
  • Evidence: ✅ Reproduced with Fast test of c8ce89b5, compared with Build (arm_release) of master 0dcf7388.
  • Cause: extractPathFromSubcolumn discards everything starting at .:, including .size0, so the new toString matching identifies this expression as path x. The safety gate then accepts an undeclared dynamic path. The predicate compares '2', while JSONAllValues stores '[1,2]', and the array tokenizer therefore prunes the matching granule. This also fails when the path is present and its array type matches, independently of the missing-path/default-value case.

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-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants