Repository navigation
Unwrap toString() when matching JSON subcolumns to JSONAllPaths/JSONAllValues text indexes - #133245
yackushevas wants to merge 7 commits into
Conversation
`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.
2ba27b2 to
4c1cfbd
Compare
|
For a JSON path declared as With |
…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.
c7ca2d4 to
570502b
Compare
|
Thanks @shihchengwei-lab — confirmed and fixed. Under the setting, 570502b declines The remaining divergence — a literal matching row-level through type coercion — predates this PR and is tracked in #119593. Covered in |
`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.
|
Workflow [PR], commit [c8ce89b] Summary: ❌
AI ReviewSummaryThis PR enables text-index pruning for Findings❌ Blockers
Pre-existing issues
Final VerdictStatus: ❌ Block Preserve indexed/scan equivalence for missing array defaults, array subcolumns, |
| 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"; |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
[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 testofc8ce89b5, compared withBuild (arm_release)of master0dcf7388. - Cause:
toStringdispatches to the active variant and renders hex61, while the index serializer keeps610000. Master returns1for bothtoStringqueries; the equivalentCAST(data.x, 'String')already returns the wrong indexed result on master, so the claimed render-safety fix remains incomplete as well.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes5 object files changed (+188.40 KiB total), 0 added.
729 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units549 translation units recompiled, 3911 s compile time in total, 549 of them have a recent master baseline. |
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); |
There was a problem hiding this comment.
[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/clickhouselocal review. - Cause:
conversionOfJSONPathIsSafeToPruneonly rejects non-default format settings and typedFixedStringpaths. It does not account for conversion-wrapped predicates whose row-level evaluation can fail on missing /NULLJSON typed paths, so the indexed plan is not semantically equivalent to the brute-force one.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
[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 testofc8ce89b5, compared withBuild (arm_release)of master0dcf7388. - Cause: The outer expression is nullable, but evaluating its inner cast is still invalid on
NULL. A second producer bypasses the same guard: withdata Nullable(JSON(x UInt8))and aNULLparent,data.xis actuallyNullable(UInt8)whilegetTypedPathTypereturns the declaredUInt8; plainCAST(data.x, 'String') = '1'again returns0indexed 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) |
There was a problem hiding this comment.
[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 testofc8ce89b5, compared withBuild (arm_release)of master0dcf7388. - 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.getTypedPathTypereturns no declared type for this dynamic path, so the values-index gate permits it.IN ('[]')also loses the row. Replacing the index declaration withINDEX paths JSONAllPaths(data) TYPE bloom_filterorTYPE tokenbf_v1(1024, 3, 0)reproduces the same regression: those callers test the default of the convertedString('') 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())) |
There was a problem hiding this comment.
[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 testofc8ce89b5, compared withBuild (arm_release)of master0dcf7388. - Cause:
extractPathFromSubcolumndiscards everything starting at.:, including.size0, so the newtoStringmatching identifies this expression as pathx. The safety gate then accepts an undeclared dynamic path. The predicate compares'2', whileJSONAllValuesstores'[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.
A text index over
JSONAllPaths(json)/JSONAllValues(json)is not used when the filter wraps the subcolumn intotoString():toString()renders the value's text representation — the same oneJSONAllValuesstores — so unwrapping it is equivalent to the already-supportedCAST(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-existingCAST(...)form:Conversion-wrapped predicates therefore decline
JSONAllValuespruning when:hasNonDefaultFormatSettings()overFORMAT_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 foundoutput_format_float_precision(rendering ofArray(Float64)) on top of the Bool and DateTime64 ones;FixedString(N), also underLowCardinality/Nullable: the rendering drops the trailing zero bytes thatJSONAllValueskeeps, at any settings. Dynamic paths never holdFixedString(stored asString);Array/MapwithFixedStringinside render consistently;String: it compares the value, which the index does not store (pre-existing forCAST);Nullableand the conversion's result is not:CAST(path, 'String')is typed asString, so a missing orNULLvalue fails at row level, and pruning the granule — the index stores a token for theNULL— would turn that failure into a result (pre-existing forCAST).toString()keepsNULLand 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):
data.host = 'needle'(control)toString(data.host) = 'needle'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 theFixedStringpath, under the settings above, for a cast to a non-Stringtype, and for a cast of aNullablepath toString(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; theCASTlines 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):
Changelog entry:
Text indexes over JSON columns: use the index for
toString()-wrapped subcolumn filters; stop pruningCAST/toString-wrapped predicates when a format setting is not at its default, the path is a typedFixedString, 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]