Repository navigation
Conversation
Statistics declared on a `JSON` column (`j JSON STATISTICS(uniq_v2)`) were rejected for every type but `basic`, and `basic` described the whole object, so a filter on a path (`j.st = 'o'`) always got the default selectivity constants. In ClickHouse#122437 all filters of a 4-table join are on JSON paths, the estimates multiply to 32 rows for a 30000-row input, and the join reordering builds hash tables from a large intermediate result. Now the declared statistics are built for each path of the column: typed paths, dynamic paths and paths in shared data (one pass over shared data per block). A path gets the declared types that support its type plus `basic`, which counts the rows without the path as NULL; `uniq`/`uniq_v2` skip NULL rows of `Dynamic`. Implicit statistics from `auto_statistics_types` are not built per path, so nothing changes for tables that declare none. The path statistics are nested in the statistics of the column, so the file name, the statistics cache, mutations, renames and merges keyed by the column are unchanged. They are written in the V4 layout under the reserved mask bit 62, which older servers skip like an unknown type. A query loads a JSON column's statistics when it reads one of its path subcolumns and keeps only those paths; the estimator registers them under the subcolumn names. Closes ClickHouse#125450 Related: ClickHouse#122437 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The statistics cache holds the statistics of a part's column as one cell, and for a `JSON` column that cell held every path deserialized. A deserialized path weighs about 60x its serialized size (each `uniq_v2` has its own arena, each path its own descriptions): measured 7.5 KB per path with `uniq_v2` + `basic` (1.76 KB with `basic` only) against about 125 bytes serialized, so a part with 2000 paths took 15 MB in the cache, the default 1 GiB cache held about 70 such parts, and a "warm" query re-read and re-deserialized most of them. Statistics read from disk now keep the statistics of their paths as the bytes they were written as, and deserialize a path when it is used: `cloneWithPaths` (the paths a query filters on), `merge` (merges of parts), while `serialize` writes the stored bytes as they are (mutations that rewrite only some columns). The cached object is never modified. Related: ClickHouse#125450 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The values of a `Dynamic` column have several types, and the literals compared
with it keep their own: `convertFieldToType` to `Dynamic` returns the literal
unchanged, and the least supertype of `Dynamic` and any type is `Dynamic`. So two
atoms on one `Dynamic` column could put a `DateTime64` and a `String` bound into
the same `PlainRanges`, and merging them (an `AND` in one PREWHERE group, an `OR`,
any filter estimated for join reordering) threw at planning:
SELECT count() FROM td AS a INNER JOIN u AS b ON a.k = b.k
WHERE a.j.d >= toDateTime64('2024-01-01 00:00:00', 3) AND a.j.d < '2024-01-15 00:00:00'
Code: 169. DB::Exception: Cannot compare ... String ... with DecimalField<Decimal64>. (BAD_TYPE_OF_FIELD)
A `JSON` path with statistics is such a column now; a top-level `Dynamic` column
already was, through its implicit `basic` statistics.
An equality on a `Dynamic` column is now estimated alone (from its statistics if
it has any, which keeps the estimate of the path filters of ClickHouse#122437), and any
other atom on it gets the constants of an expression, so the ranges of such a
column are never merged. A typed path of `Variant` type does not fail and is not
changed.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A typed path of type `JSON` (`j JSON(a JSON) STATISTICS(...)`) got a nested `ColumnStatistics` with `basic` for each of its own paths, built on every insert and merge, but nothing reads them: `cloneWithPaths` and the estimator look up the paths of the outer column only, so a filter on `j.a.b` got the default constants anyway. Such a typed path now gets no statistics. Flattening the nested paths would need a rule for a column with typed paths `a JSON` and `a.b`, which both receive `a.b`. Related: ClickHouse#125450 Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `optimize_functions_to_subcolumns = 1` (the default) `isNull(j.a)` on a `Nullable` typed path becomes `notEquals(j.a.null, 0)`, and `isNotNull(j.a)` becomes `not(j.a.null)`. Master maps `<col>.null` to `<col>` for a top-level column when it loads statistics and when it estimates, but the path rules of this PR did not cover the `.null` form, so the estimate fell back to the defaults (`a[990]` instead of `a[750]` on 1000 rows with 750 NULLs): - `getRequiredJSONPaths` turned `j.a.null` into the path `a.null`, which has no statistics, so the statistics of `a` were not kept. It now also adds the path behind a `.null` name, as `getStatisticsFilesToLoad` does for columns. - `tryGetNullMapParentColumn` looked the parent up among top-level columns only. It is now a member that uses `tryGetColumnType`, like the other column lookups of the estimator, which finds a path that has statistics. Related: ClickHouse#125450 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the comment restating the JSON-typed-path early return and shorten the serialized path statistics member comment. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (codex) plus my own review, over 4 review rounds of this design.
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-49:20261110-154501 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-publish-slot-34:20261110-162000 |
|
Workflow [PR], commit [95bd5f0] Summary: ❌
AI ReviewSummaryThe PR builds per-path Findings❌ Blockers
Tests
Missing context / blind spots
Final VerdictStatus: ❌ Block Reject oversized sketch counts before allocation and cover the metadata-free |
|
cc @hanfei1991 @nickitat, could you review this and add the |
…ounts Since ClickHouse#130202 the statistics estimate rounds the row count instead of truncating it, and CI tests the merge with master. 3000 * 0.33 * 0.33 = 326.7 rows for `x0` and `x3` is now shown as 327; the join order is the same. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Every other case of 05620_statistics_json_paths declares `uniq_v2`, so the `Dynamic` support of `uniq` had no test. With half of the rows `NULL`, the estimate is 500 rows; it is 250 when `NULL` is counted as a value, and master rejects the declaration. `basic` is declared explicitly because it keeps the `NULL` count, and `auto_statistics_types` is randomized in CI. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes11 object files changed (+120.17 KiB total), 0 added.
716 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 units347 translation units recompiled, 2629 s compile time in total, 347 of them have a recent master baseline. |
CI finish ledger - db892c3Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:clickhouse-maint-slot-12:20261110-234000 |
|
Fixing PR for the |
…part files after the upgrade After the restart, the upgraded server executes a MERGE_PARTS or MUTATE_PART entry whose result the other replica already committed under the previous release. checkPartChecksumsAndCommit compares the new part with the ZooKeeper part header written by the old release. Releases change the byte format of uncompressed part files: statistics.packed is registered with file_hash only, so it lands in the "hash of uncompressed files" bucket, and its content changed in 26.7 (auto_statistics_types default) and in 26.11 (ClickHouse#123950 adds the sum to basic statistics). The task then logs CHECKSUM_DOESNT_MATCH at error level, removes the local part and fetches the replica's part. The upgrade guide (docs/guides/oss/update.mdx) documents this message as expected while replica versions differ, and the statistics author confirmed it on ClickHouse#130674, but the post-upgrade log scan treated it as a failure. Filter the line only when "hash of uncompressed files doesn't match" is the sole clause. Divergent column data ("uncompressed hash of compressed files"), both clauses together, a different number of files and the KILL MUTATION "different columns hash" case still fail the job. The Upgrade check is the only CI job that reports these lines (the stress tests scan only "<Error>.*Application"), so a broader filter on "is not byte-identical to data on another replicas" would remove the only CI detector of divergent column data after replicated merges and mutations. Validated by running the extracted scan on the Upgrade check log of ClickHouse#130547 (1 line -> 0) and on 7 control lines (7 -> 5, every other shape kept), with GNU grep 3.11 locally and inside clickhouse/stress-test. Changing "Code: 40" to "Code: 41" in the new pattern restores both results. Related: ClickHouse#103395 Related: ClickHouse#130674 Co-Authored-By: Claude Opus 5.5 <[email protected]>
| @@ -518,10 +502,28 @@ bool ConditionSelectivityEstimator::extractAtomFromTree(const StorageMetadataPtr | |||
|
|
|||
| if (metadata) | |||
There was a problem hiding this comment.
[Major] The new Dynamic / JSON-path fixes only run under if (metadata), but StatisticsDerivation still calls estimateRelationProfile(nullptr, nullptr, prewhere_node) in src/Processors/QueryPlan/Optimizations/Cascades/StatisticsDerivation.cpp:423. On that path column_type stays null, so a predicate like d = toDateTime64(...) OR d = '2024-01-16 10:00:00' on a Dynamic column or dynamic JSON path still builds two range atoms and tryToMergeClauses ends up comparing incompatible Field types again. The same gap also bypasses the new j.n.null -> j.n mapping there.
Please either derive the effective column type/null-map parent from the DAG node when metadata is absent, or avoid using the new path/Dynamic estimator logic from the metadata == nullptr call sites until you can provide that type information.
|
@groeneai please fix build |
`StatisticsType::JSONPaths = 62` replaces the local `PATH_STATISTICS_MASK_BIT` constant in `Statistics.cpp`, so the bit is reserved in the enum itself and a new statistics type cannot take it by accident. The value is unchanged, so the `statistics.packed` layout is identical. It is not a declarable type: `stringToStatisticsType` does not know it and the statistics factory has no creator for it. Review request: ClickHouse#130547 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master enabled the `modernize-use-nodiscard` clang-tidy check after this PR was opened, so `Build (arm_tidy)` failed on the merge with master on the 7 const member functions this PR adds to `ColumnStatistics` and `ConditionSelectivityEstimator`. No call site discards their result. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`ColumnStatistics::deserialize` allocated `stat_size` bytes for the `JSONPaths` payload before reading it, so a damaged statistics file could request any amount of memory: a 39-byte input claiming 4 GiB raised the peak RSS by 4 GiB before `CANNOT_READ_ALL_DATA`. Read the payload through a `LimitReadBuffer` instead, which allocates only the bytes that are present and still throws `CANNOT_READ_ALL_DATA` on a short read. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The previous reader allocated the declared size and failed with `std::length_error`; it now fails with `CANNOT_READ_ALL_DATA`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Done in ebab13e: the |
…istics # Conflicts: # src/Storages/Statistics/StatisticsBasic.h
`JSONPaths` is now a statistics type like the others: an `IStatistics` in its own files that builds, merges and (de)serializes the statistics of the paths of a `JSON` column. A `JSON` column that declares statistics gets it from `MergeTreeStatisticsFactory`; it still cannot be declared. `ColumnStatistics` and `Statistics.h` no longer know about JSON: the estimator and the part loader reach the paths through `getStats()`, and `ColumnStatistics::cloneWith` replaces the entry with the projection to the required paths. The entry also stores its row count, which its merge needs to count the rows of a part without a path as NULL. Estimates are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
rschu1ze
left a comment
There was a problem hiding this comment.
@hanfei1991 What the bot is building here seems completely overblown. All we need is the ability to create uniq_v2 and basic statistics on JSON columns but the PR does lots of changes outside these two statistics.
|
Agreed, I'll cut it down to Removed: Outside the two statistics I keep only what makes them used: loading the statistics of I'll link the commit here. |
Review of rschu1ze on ClickHouse#130547: the PR should only make `basic` and `uniq_v2` work on `JSON` columns. Each of the two now keeps its state per path itself, next to the state of the column: `StatisticsBasic` behind a new feature bit (older servers skip it), `StatisticsUniqV2` after the state of the column (`uniq_v2` was not allowed on `JSON` before). Both build the paths only when declared explicitly, not when added by `auto_statistics_types`. Removed: `StatisticsJSONPaths` and the `JSONPaths` statistics type, other statistics types on paths, `uniq` / `uniq_v2` on top-level `Dynamic`, the projection of the loaded statistics to the required paths and their lazy deserialization, and the `.null` handling for paths. Kept outside the two statistics: the statistics of a `JSON` column are loaded for a query on one of its paths, the estimator looks a path up in the statistics of its subcolumns, and an atom on a `Dynamic` path is estimated alone if it is an equality, so that literals of two types on one path are never compared. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…riptions A corrupted statistics file could set the bit on another type. The cache weight of the path statistics did not include their descriptions. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Done in 0556d90 (and 95bd5f0 for two review findings): the PR is now +401/-16 in 12 files instead of +692/-37 in 17. |
| String path; | ||
| readStringBinary(path, buf); | ||
| auto path_stats = std::make_shared<StatisticsUniqV2>(stat, StatisticsUtils::getJSONPathType(*json_type, path)); | ||
| path_stats->deserialize(buf, version); |
There was a problem hiding this comment.
[Blocker] Reject impossible nested sketch sizes before allocating
This new path reader reaches CombinedCardinalityEstimator::read, which forwards a MEDIUM state to HashTable::read without enforcing the sketch's small upper bound. A valid empty parent sketch followed by one dynamic path whose state contains is_null = false, container tag 2, and a varint count of 1ULL << 36 reaches HashTable.h:1768-1775: the count passes its generic 100'000'000'000 limit and requests roughly 1 TiB before reading any keys, even if the file ends immediately afterward.
Statistics cache loading runs under MemoryTrackerBlockerInThread, so the querying user's memory limit does not contain this allocation. A damaged or supplied part can therefore turn a tiny statistics payload into a server-wide allocation request. The issue is inherited from the shared sketch decoder; please enforce its representation-specific count limit before allocation there, covering both the parent and the new path states, and add a regression for a truncated nested MEDIUM state with an oversized count.
There was a problem hiding this comment.
Not changing this here: the path state is read by the same collector->deserialize call as master's top-level uniq_v2 state, and master's shared decoder already requests 1.00 TiB for the same sketch state (SELECT finalizeAggregation(CAST(unhex('02808080808002') AS AggregateFunction(uniqCombined64(12), UInt64))) gives Code: 241 ... (total) memory limit exceeded: would use 1.00 TiB (attempt to allocate chunk of 1.00 TiB)). A size bound in CombinedCardinalityEstimator::read is a fix of that shared decoder, separate from this PR.
Closes: #125450
Related: #122437
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Statistics
basicanduniq_v2declared on aJSONcolumn (for examplej JSON STATISTICS(basic, uniq_v2);uniq_v2was rejected before) are built for every path of the column, including dynamic paths and paths stored in shared data, and are used to estimate filters on paths. Closes #125450.Description
Only
basicwas accepted on aJSONcolumn, and it described the column only, so filters on paths got default constants. In #122437 every filter of a 4-table join is on paths, and join reordering hashes a 3M-row intermediate result.Change.
basicanduniq_v2declared on aJSONcolumn also keep their state for each path, typed, dynamic and in shared data:StatisticsBasicbehind a new feature bit (older servers skip it),StatisticsUniqV2after the state of the column.basiccounts the rows without a path asNULL, anduniq_v2does not countNULLof aDynamicpath. Only explicit declarations build paths, notauto_statistics_types, so an existingJSON STATISTICS(basic)changes and nothing else does. A query on a path loads the statistics of its column, and the estimator looks the path up among their subcolumns. Literals compared with oneDynamicpath may differ in type, so an equality on it is estimated alone and other comparisons get constants (this also avoidsCannot compareat planning for aDynamiccolumn with statistics).Not covered: other statistics types on paths,
Nullable(JSON), typed paths of typeJSON,IS NULLon aNullabletyped path when rewritten to<path>.null, and part pruning. A query on one path loads the statistics of all paths of the column. Older servers rejectuniq_v2onJSON.Validation. The test is the #122437 reproducer at 1/100 scale (hash tables are built only from base tables; master fails at
CREATE), a path in shared data, a path missing from a part (also after a merge), and literals of two types on one path. Disabling any one piece of the change turns it red.Workflow [PR]
Sync PR [sync-upstream/pr/130547]