Repository navigation
Add a type-aware Bloom filter index for JSON - #113022
rorylshanks wants to merge 212 commits into
Conversation
|
Workflow [PR], commit [4d85abc] Summary: ❌
AI ReviewSummaryAdds the experimental Missing context / blind spots
Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block. Correct all three false-negative classes, narrow the prefix guard, and add focused stateless regressions. |
Resolve documentation migration conflicts for ClickHouse#113022.
Document that negating `BoolMask` preserves unknown Bloom-filter hits and add a same-granule regression for `notEquals` and `notLike`. Related: ClickHouse#113022
Coerce comparison constants to concrete JSON subcolumn types before serializing Bloom-filter probes. Keep direct, identity-cast, and `String`-cast acceleration, and decline value-changing casts whose stored representation cannot be recovered safely. Related: ClickHouse#113022
Skip direct and identity-cast matches while a JSON subcolumn still has type `Dynamic` or `Variant`. Query execution compares the concrete alternative and may coerce the constant first, so hashing the abstract literal can prune matching granules. Initialize `JSONAllValuesIndexInfo::match_kind` to satisfy clang-tidy and make existing index tests use typed paths. Add a regression covering inferred `DateTime64` compared with `toDate` for `bloom_filter` and `tokenbf_v1`. Related: ClickHouse#113022 Related: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113022&sha=0ba7287420b3d076dcb039f9cb854082b96555ef&name_0=PR&name_1=Build%20%28arm_tidy%29
Derive the cast match kind only after rejecting unsupported casts, so `cppcoreguidelines-init-variables` no longer rejects the helper. Related: ClickHouse#113022
Inspect child types before building probes so composite subcolumns containing `Dynamic` or `Variant` cannot drive unsafe index skipping. Add coverage for an inferred `Array(Dynamic)` path. Related: ClickHouse#113022 Related: ClickHouse#113022 (comment)
Set `session_timezone` explicitly so randomized CI settings cannot change the `Date` to `DateTime64` comparison before index analysis. Related: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113022&sha=0be0a703c85cf16b7ca5c1c54ad1081f5db9af8c&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29 Related: ClickHouse#113022
Document equality and `IN` support for `ngrambf_v1`, `tokenbf_v1`, and `sparse_grams`, and link the full function-support table. Related: ClickHouse#113022 (comment) Related: ClickHouse#113022
… binary representation A complex value in the shared data of `JSON` (e.g. an array of objects) was deserialized into a temporary column to emit its tokens. `SerializationObject::deserializeBinary` puts the paths of an object without dynamic paths into shared data, deserializing every value into a `Field` only to find where it ends, and the index then deserialized every nested complex value again for each level of nesting. It took most of the time of building the index for objects with nested arrays of objects. Arrays and objects with only shared data (no typed paths, no paths to skip, `max_dynamic_paths = 0`), and arrays of numbers and strings, are now emitted directly from their binary representation, in the same order and with the same tokens as before, so the index files do not change. Other values still use a temporary column. The types of values are decoded once and remembered by their binary encoding. On 2M rows of JSON with nested arrays of objects, building the index takes 22 s instead of 60 s. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Every granule of `jsonbf_v1` lists all paths with their scopes and types. Reading a granule copied all of them into strings and created a default `FormatSettings` for every path, although a condition uses only a few paths. Now the scopes of unused paths are skipped, and the path is appended without zero-filling. For a large part with hundreds of paths per granule, the analysis of the index for a condition on one `JSON` path became 2.5 times faster. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ecoding Assign the encoded type from a `std::string_view` slice instead of passing `data` to `String::assign`. CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113022&sha=301477bfda8bdfd59112d29da7223871842189f0&name_0=PR&name_1=Build%20%28arm_tidy%29 PR: ClickHouse#113022 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…queries of the JSON Bloom filter perf tests The setting was in the `<settings>` block, which the performance test applies to both the new and the reference server. The reference server does not know the setting yet, so every `json_bloom_filter_*` perf test failed with `Unknown setting 'allow_experimental_json_bloom_filter_index'`. Only adding the `jsonbf_v1` index needs it, and these queries are already skipped on the reference server by `do_not_check_in_pr`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113022&sha=b9f2f8fc33ac529a71a5be3edabe50795b576bb0&name_0=PR ClickHouse#113022 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ADD INDEX IF NOT EXISTS` `ADD INDEX IF NOT EXISTS` of a `jsonbf_v1` index that already exists adds nothing, so it must not throw `SUPPORT_IS_DISABLED` without `allow_experimental_json_bloom_filter_index`. Replay the index names in the order of the commands to find out whether the index exists at the point of the `ADD INDEX`, so that `DROP INDEX idx, ADD INDEX IF NOT EXISTS idx ...` still counts as adding a new index. Co-Authored-By: Claude Opus 5.5 <[email protected]>
With parallel replicas the plan is nested, and the `pretty` format prefixes the lines of the nested steps with `│`, so `05244_json_bloom_filter_typed_path_defaults` and `05259_json_bloom_filter_shared_nested_values` failed in `Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel)`. Use the `legacy` format without parallel replicas, as other `jsonbf_v1` tests do. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113022&sha=b9f2f8fc33ac529a71a5be3edabe50795b576bb0&name_0=PR ClickHouse#113022 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@rorylshanks Is there a design RFC for the new index? Would the text index cover your use case? |
|
Hey @rschu1ze! I didn't make an RFC for this one, would you prefer if I made one? RE the text index, I have a PR for that here #114613 but the text index and bloom filters have vastly different storage requirements on disk and so it is nice to have the option of both! Ultimately the current impl of the JSONAllValues on the text index is unsafe. We need an index that stores the type so we can correctly compare types that coerse. |
|
We can't merge a 6.5k LOC PR without a structured design document. Looking at the PR message, it is not clear at all what the new code does. In that sense, please open an RFC first so people can comment. Thanks. |
…es-bloom-indexes Conflicts: - `InterpreterHypotheticalObjectQuery.cpp`: keep the renamed `allow_suspicious_indexes` setting. - `MergeTreeIndexJSONSubcolumnHelper.cpp`: keep both master's typed-path handling and the PR's comparison format settings. - `MergeTreeIndexReader.cpp`: master opens only the regular substream and lets the text index open its own; keep that and also open the `JSONBloomFilterValues` substream of `jsonbf_v1` with a small read buffer. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…now defined for all sources Co-Authored-By: Claude Opus 5.5 <[email protected]>
…TreeContext` in master Co-Authored-By: Claude Opus 5.5 <[email protected]>
…es-bloom-indexes # Conflicts: # src/Storages/MergeTree/registerStorageMergeTree.cpp
…es-bloom-indexes Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
`IMergeTreeIndex::getAllSubstreamsInPart` is no longer virtual: it probes every substream of `getPotentialSubstreams` in the part. The override in `MergeTreeIndexJSONBloomFilter` did not compile (`only virtual member functions can be marked 'override'`), and the base implementation already returns both `.idx2` substreams when they exist, so remove it. Skip index conditions now get a lazy `IsShadowingColumn` callback instead of a precomputed `NameSet` of columns shadowing Map key subcolumns. Do the same for `jsonbf_v1`: look the predicate column name up in the metadata snapshot on demand, and refuse it when it has the shape of a Map key subcolumn or names a subcolumn of the indexed column that belongs to another column. This keeps the previous semantics without collecting the table's column names per condition. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113022&sha=feaeb3cad3b47baf60a3716a219878d5e83abf85&name_0=PR&name_1=Fast%20test PR: ClickHouse#113022 Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
The setting is not in any release yet, and the settings history check requires new settings to be recorded under the current version. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113022&sha=feaeb3cad3b47baf60a3716a219878d5e83abf85&name_0=PR&name_1=Style%20check PR: ClickHouse#113022 Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
…d paths A missing non-`Nullable` typed path of a `JSON` column reads as its type's default, which `jsonbf_v1` does not index, so a granule where the path is always absent has no directory entry for it. `CAST(j.x AS Nullable(UInt8))` keeps that default as a value, but `tryMatchJSONPresencePath` accepted the cast because its result is `Nullable`, so `CAST(j.x AS Nullable(UInt8)) = 0`, `... IN (0)` and `isNotNull(...)` skipped granules with matching rows. Accept a cast of a non-`Dynamic` argument for the presence fallback only when the argument itself can be NULL, so that a missing path is NULL before and after the cast. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
… definition `allow_experimental_json_bloom_filter_index` was checked only for `INDEX` clauses written in a `CREATE` query. `CREATE TABLE ... AS src` and `CLONE AS src` copy the indexes of another table later in `getTableProperties`, and a full-definition `ATTACH TABLE` runs with `LoadingStrictnessLevel::ATTACH`, so both created new tables with the index while the setting was disabled. Check the final `properties.indices` whenever `isFreshTableDefinition` holds, like the other checks of user-supplied definitions. Replays of stored metadata, including short `ATTACH TABLE`, still work without the setting. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
… read `MergeTreeIndexReader` created a marks-based stream for every substream up front. For a part with more than one mark, that started loading the marks of the `JSONBloomFilterValues` substream, opened its file and seeked it to every granule, although `jsonbf_v1` reads it only at the offsets stored in the regular substream, and only for filters larger than the inline limit. Presence predicates and parts with inline filters paid for it anyway. Read that substream as a whole file without marks, like an index with a single mark: its file is opened by the first read, and the reader no longer seeks it to granule marks. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
`ConvertEmptyStringComparisonToFunctionPass` rewrites `s = ''` to `empty(s)`. Since ClickHouse#125011 it does so for `Nullable(String)` too, and since ClickHouse#128092 for `LowCardinality(String)`, so comparisons of `Nullable(String)` typed paths and of `Dynamic` subcolumns such as `j.x.:String` with an empty string no longer reached the `equals` analysis of `jsonbf_v1`, and the index was not used for them. Analyze `empty` of a string like the comparison with an empty string, as `MergeTreeIndexBloomFilter` does. A missing non-`Nullable` typed path still reads as its default, which is not indexed, so `j.s = ''` for such a path keeps skipping the index. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113022&sha=c543bed2acf878e6046ff4920f52b901e3d77d7f&name_0=PR&name_1=Fast%20test PR: ClickHouse#113022 Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
Two master changes made comparisons that used to throw return a result, and the tests pinned the old exceptions: - ClickHouse#122245 compares a string constant with an integer outside the range of the column type in a wider integer type, so `UInt64 = '-42'` is `0` instead of `TYPE_MISMATCH`. `05101` now uses `'42.5'`, which integer runtime types still fail to parse, for the exception, and checks that `'-42'` matches nothing. - ClickHouse#124680 compares decimals of different scales exactly, so rescaling `Decimal(18, 2)` to the scale of `toDecimal64(1, 3)` no longer throws `DECIMAL_OVERFLOW`. `05103` now checks that the index keeps the matching row next to a value whose rescaling overflows. Both are intended behaviour. The index stays conservative for them: it keeps the granules where the conversion of the constant fails. Without the overflow check (`decimal_check_overflow = 0`) execution rescales with wraparound, which is why the index still keeps decimal types whose rescaling may overflow; the comment now says so. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113022&sha=c543bed2acf878e6046ff4920f52b901e3d77d7f&name_0=PR&name_1=Fast%20test PR: ClickHouse#113022 Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
…anularity_bytes = 0` A table without adaptive granularity logs a warning at creation when `min_bytes_for_wide_part` is not zero, which the test randomization can set, and the warning in stderr fails the test, as in `05497`. `05244` already sets it explicitly. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113022&sha=c543bed2acf878e6046ff4920f52b901e3d77d7f&name_0=PR&name_1=Fast%20test PR: ClickHouse#113022 Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
… = ''` `FunctionToSubcolumnsPass` rewrites `empty(s)`, which is what `ConvertEmptyStringComparisonToFunctionPass` makes of `s = ''`, to `s.size = 0`. Since ClickHouse#125011 both passes also apply to `Nullable(String)`, so `j.ns = ''` for a `Nullable(String)` typed path and ``j.x.:`String` = ''`` reach the index as `equals(j.ns.size, 0)` and ``equals(j.x.:`String`.size, 0)``, and `jsonbf_v1` was not used for them. The previous commit handled only `empty(s)`, which remains with `optimize_functions_to_subcolumns = 0`. Analyze the comparison of the size subcolumn of a `JSON` string subcolumn with zero as the comparison of the subcolumn with an empty string. A name that is itself a `JSON` path, such as a path whose last key is `size`, is not a size subcolumn. Verified locally: `05101`, `05102`, `05103`, `05106`, `05244` and `05497` pass. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113022&sha=c543bed2acf878e6046ff4920f52b901e3d77d7f&name_0=PR&name_1=Fast%20test PR: ClickHouse#113022 Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
| converted = tryConvertFieldToType(integer, *target_type, nullptr, format_settings, /* strict= */ true); | ||
| } | ||
| else | ||
| converted = tryConvertFieldToType(value, *target_type, source_type.get(), format_settings, /* strict= */ true); |
There was a problem hiding this comment.
❌ Blocker: probe conversion does not preserve String/FixedString comparison semantics.
For j JSON(s String) containing {"s":"abc"}, j.s = toFixedString('abc', 5) is true: FunctionsComparison uses a zero-padded comparison. However, tryConvertFieldToType returns the padded constant unchanged when converting it to String, so this probe hashes abc\0\0, while the stored token hashes abc. The index can therefore discard the matching granule. This also affects runtime String values in Dynamic paths.
The shared builder has the same problem for hasAny/hasAll on Array(String) with [toFixedString('a', 3)]: execution casts the arrays to their common type and strips the padding, whereas the probe retains it. Conversely, a FixedString(3) path compared with 'abcd' reaches column->insert with an overlong value and introduces TOO_LARGE_STRING_SIZE where an unindexed equality simply returns false.
Please handle these comparisons at the shared probe boundary: decline unsafe cases or normalize both stored tokens and probes according to the operator's semantics. Add indexed-versus-unindexed regressions for scalar equality and array membership, including padding and differing widths.
| if (is_column_shadowing_subcolumn(column_name)) | ||
| return std::nullopt; | ||
| auto match = tryMatchJSONSubcolumn(column_name, header); | ||
| if (!match || match->indexes_missing_values || match->role != JSONBloomRole::Scalar || !path_matcher.shouldIndex(match->logical_path)) |
There was a problem hiding this comment.
❌ Blocker: typed containers can match without having an entry for their parent path in the directory.
For j JSON(a Array(Array(Int64))), a row {"a":[[]]} satisfies j.a = [[]]. makeValueProbes declines the whole-array probe, but this helper accepts the exact typed path, and the default-value check accepts [[]] because it differs from []. Evaluation then requires granule.hasPath("a").
The extractor never creates that entry: typed arrays have is_dynamic = false, so emitRange does not record complex presence, and recursing through [[]] reaches an empty scalar range without emitting any value token. The matching granule is therefore discarded. Typed tuples similarly emit descendant paths rather than their parent, and arrays containing only null elements have the same absence of tokens. Both equality and IN use this presence fallback.
Please restrict the fallback to representations whose directory presence is guaranteed, or record container presence independently of their scalar leaves. Add a standalone indexed-versus-unindexed regression for [[]] and cover the other typed container forms handled by this helper.
| if (!match || match->typed_dynamic || match->indexes_missing_values || match->role != JSONBloomRole::Scalar | ||
| || !isDynamic(match->type) || !path_matcher.shouldIndex(match->logical_path)) |
There was a problem hiding this comment.
❌ Blocker: a declared Dynamic path is not equivalent to directory presence for JSONAllPaths.
With j JSON(x Dynamic), JSONAllPaths(j) includes 'x' even for {} when type_json_skip_null_typed_paths = 0 (the default). This guard nevertheless accepts it: the match has type Dynamic, typed_dynamic = false, and indexes_missing_values = false. The extractor skips the null discriminator, so the granule has no x directory entry and FUNCTION_EXISTS prunes a matching row.
For example, put (1, '{}') and (2, '{"x":1}') in separate granules. WHERE has(JSONAllPaths(j), 'x') must return both IDs, but the new index rejects the first granule. The same helper supplies the other supported JSONAllPaths predicates.
Please explicitly account for paths declared in the indexed DataTypeObject instead of using the result type to identify them, and add this regression with type_json_skip_null_typed_paths = 0 explicitly set.
| if (!header.has(column_name_string) || !isObject(header.getByName(column_name_string).type)) | ||
| continue; | ||
| const auto & object_type = assert_cast<const DataTypeObject &>(*header.getByName(column_name_string).type); | ||
| if (subcolumn_name.empty() || subcolumn_name.starts_with("^") || subcolumn_name.starts_with("@")) |
There was a problem hiding this comment.
@ or ^.
A quoted access such as j.`@timestamp` lowers to the ordinary subcolumn name j.@timestamp. Only a prefix followed by a backtick denotes a special combined/sub-object carrier; DataTypeObject::tryGetPrefixedSubcolumn and the existing isPrefixedSubcolumn helper make that distinction explicitly. This broader check rejects the literal field before resolving its type.
Consequently, a predicate on a regular @timestamp field always scans without jsonbf_v1 (or throws INDEX_NOT_USED when forced), although the extractor stores its tokens. This affects a common log-event field name and also disables its JSONAllPaths presence probes.
Please reject only the actual prefixed carrier syntax and add a focused forced-index regression on a quoted literal field beginning with @ or ^.
Related: #113376
Related: #118577
This PR adds
jsonbf_v1, an experimental data-skipping index for aJSONcolumn.The index can skip granules for these conditions:
INon a JSON path.has,hasAny, andhasAllon arrays.Mapvalues, and fields of namedTuplevalues.isNotNull(data.path), andhas,hasAny,hasAll,indexOf,IN, andarrayJoinonJSONAllPaths(data). These conditions replace abloom_filterindex onJSONAllPaths.The index keeps the values of different paths apart. It also records the runtime types of each path. A
Dynamicpath can hold values of different types. A comparison can convert the constant, or it can throw an exception. The index applies the same rules. ClickHouse reads every granule that can contain a match or an exception.Each granule stores a sorted list of its paths and one Bloom filter for each path. A query reads only the filters of the paths that it uses.
Benchmark. JSONBench with 1,000,000 Bluesky records, one thread, AMD Ryzen 9 5950X, commit
54e7de31c26. Each time is the median of 16 warm runs (5 runs for the insert). The server measured each time, so each time includes query analysis. The results were the same with and without the index.didequality, 2 rowscommit.cidequality, 1 rowcommit.record.textequality, no rowshas(JSONAllPaths(data), ...), no rowskind = 'commit', most rowsINSERT SELECT, 1M rowsThe index is 7.17 MB. The insert reads JSON that is already parsed. On wide synthetic JSON (200,000 rows, 419 paths per row), the index is 61 MiB and the
JSONcolumn is 364 MiB.The tests
05106_json_bloom_filter_shared_typesand05107_json_bloom_filter_dynamic_mapsetmap_serialization_versionandmap_serialization_version_for_zero_level_partstobasicuntil #118577 is merged.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Adds the experimental
jsonbf_v1data-skipping index forJSONcolumns. It speeds up equality, array membership, and path presence conditions. Enable it with the settingallow_experimental_json_bloom_filter_index.Workflow [PR]
Sync PR [sync-upstream/pr/113022]