Skip to content

Build statistics for every path of a JSON column - #130547

Open
groeneai wants to merge 17 commits into
ClickHouse:masterfrom
groeneai:feat/json-path-statistics
Open

groeneai wants to merge 17 commits into
ClickHouse:masterfrom
groeneai:feat/json-path-statistics

Conversation

@groeneai

@groeneai groeneai commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #125450
Related: #122437

Changelog category (leave one):

  • New Feature

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

Statistics basic and uniq_v2 declared on a JSON column (for example j JSON STATISTICS(basic, uniq_v2); uniq_v2 was 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 basic was accepted on a JSON column, 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. basic and uniq_v2 declared on a JSON column also keep their state for each path, typed, dynamic and in shared data: StatisticsBasic behind a new feature bit (older servers skip it), StatisticsUniqV2 after the state of the column. basic counts the rows without a path as NULL, and uniq_v2 does not count NULL of a Dynamic path. Only explicit declarations build paths, not auto_statistics_types, so an existing JSON 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 one Dynamic path may differ in type, so an equality on it is estimated alone and other comparisons get constants (this also avoids Cannot compare at planning for a Dynamic column with statistics).

Not covered: other statistics types on paths, Nullable(JSON), typed paths of type JSON, IS NULL on a Nullable typed 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 reject uniq_v2 on JSON.

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]

groeneai and others added 6 commits November 9, 2026 11:11
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
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.

# Sev Finding Verdict Evidence / action
1 ⚠️ Literals of two types on one Dynamic value reach the range merge of the selectivity estimator, which throws Cannot compare (also on plain Dynamic columns in 26.8 / 26.10) AGREE, fixed @ d646485 an equality on Dynamic is estimated alone, other atoms get constants; 3 test lines red before
2 ⚠️ A typed path of type JSON built statistics for its sub-paths that no query could read AGREE, fixed @ e9274b8 such a path gets no statistics; stated in the docs and the description
3 ⚠️ Part pruning by statistics does not use path statistics DISAGREE (out of scope: separate PR) this PR covers estimation; stated in the description
4 💡 Nullable(JSON) is not covered; an existing JSON STATISTICS(basic) is now built per path AGREE stated in the description
5 💡 The number of path statistics grows with the number of distinct paths AGREE by design (#125450: every path); stated in the docs
6 💡 IN on a Dynamic path gets the default constant noted equality only, as in #122437
7 ⚠️ IS NULL / IS NOT NULL on a Nullable typed path, rewritten to <path>.null by optimize_functions_to_subcolumns (default), did not use the path statistics AGREE, fixed @ c4ee1d2 the .null rule of the loader and the estimator also maps a path's .null to the path; 2 test lines red before
8 ⚠️ With typed paths n Nullable(...) and n.null both declared, j.n.null = 0 is estimated as j.n IS NOT NULL DISAGREE (out of scope: separate PR) master's .null rule already reads a top-level column named `n.null` next to n this way (such a column is allowed); with a dynamic n.null the name resolves to the NULL map of n; estimate only, the result is right
9 ⚠️ A part written before the upgrade for JSON STATISTICS(basic) has no path statistics, so the estimator skips one kind of part until a merge DISAGREE on master too the estimator skips parts whose statistics differ in structure (any change of a column's statistics without MATERIALIZE STATISTICS); with the old part first the estimate is master's; a merge or MATERIALIZE STATISTICS rebuilds
10 💡 "A row without the path counts as NULL" is not true for a non-Nullable typed path DISAGREE a typed path has a value in every row (the type default), so no row lacks it; the sentence is about dynamic and shared-data paths

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-49:20261110-154501

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master the test's first CREATE (j JSON ... STATISTICS(uniq_v2)) fails with Code: 708; with the change the output matches the reference in 54 of 54 runs (53 randomized).
b Root cause explained? Only basic accepted JSON, and it describes the whole object, so every filter on a path got the default factors: in #122437 x1 was estimated at 32 of 30000 rows, and greedy reordering built hash tables from the 3M-row x0 JOIN x1 result.
c Fix matches root cause? Yes: it supplies the missing input, statistics per path, and the estimator finds them by the subcolumn name. Nothing changes for columns without statistics.
d Test intent preserved / new tests added? New SQL test 05620_statistics_json_paths: the #122437 reproducer at 1/100 scale, a path in shared data, a path missing from a part (also after a merge and a mutation), literals of two types on one Dynamic path, IS NULL / IS NOT NULL on a Nullable typed path.
e Both directions demonstrated? Master: 708 at the first CREATE; with the change: the reference. Twelve code mutations (path statistics, shared data, NULL padding, merges, serialize, the Dynamic guard, the <path>.null mapping) each change the output.
f Fix is general across code paths? Every builder (insert, merge, MATERIALIZE STATISTICS), writer (part writer, partial-rewrite mutation), loader (with and without required columns, prewarm) and estimator lookup, for typed, dynamic and shared-data paths; ranges of a Dynamic value are never merged on any estimator path.
g Fix generalizes across inputs (params/datatypes/wrappers)? Typed numeric and String paths with tdigest, uniq, countmin, minmax; Dynamic paths with NULL rows; shared data; absent paths; Wide and Compact parts; DateTime64 and String literals on one path. Nullable(JSON) keeps today's behaviour (708); a typed path of type JSON gets no statistics.
h Backward compatible? (maintainer-approved exception only) No file version, setting or default changes. Older servers skip the path statistics (a reserved mask bit); auto_statistics_types are not built per path, so tables that declare none are unchanged.
i Invariants and contracts preserved? The statistics of a path cover every row (a row without the path counts as NULL); objects in the statistics cache are never modified; serialized and deserialized path statistics never coexist in one object.

Session id: cron:clickhouse-publish-slot-34:20261110-162000

@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [95bd5f0]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR builds per-path basic and uniq_v2 statistics for explicitly annotated JSON columns and uses them for filter estimates. Review of commit 95bd5f0bd65ddaf8936541910a5adce8f88c6bc1 found an unsafe allocation in nested sketch deserialization and confirmed that the previously reported metadata-free Dynamic estimation gap remains. Changes are required.

Findings

❌ Blockers

  • src/Storages/Statistics/StatisticsUniqV2.cpp:172: The new nested reader accepts impossible sketch sizes through the shared decoder. An empty parent sketch followed by one dynamic path with is_null = false, container tag 2 (MEDIUM), and a varint count of 1ULL << 36, followed by EOF, reaches CombinedCardinalityEstimator::read and then HashTable::read. The generic count limit permits this value, and the table requests roughly 1 TiB before checking that any keys exist. Statistics cache loading bypasses the querying user's memory accounting. Enforce the sketch's representation-specific size limit before allocation in the shared decoder, covering parent and path states.

⚠️ Majors

  • src/Storages/Statistics/ConditionSelectivityEstimator.cpp:543: The Dynamic guard still requires metadata, but StatisticsDerivation::deriveReadStatistics passes null metadata at src/Processors/QueryPlan/Optimizations/Cascades/StatisticsDerivation.cpp:423. With make_distributed_plan = 1 and enable_cascades_optimizer = 1, a PREWHERE expression such as j.d = toDateTime64('2024-01-15 10:00:00', 3) OR j.d = '2024-01-16 10:00:00' can still merge incompatible decimal and string range bounds and throw Cannot compare during planning. Derive the effective type from the DAG/statistics or pass the storage metadata on this path. This is the existing unresolved finding; no duplicate inline comment was posted.
Tests
  • ⚠️ Add a decoder regression with an oversized nested MEDIUM count and no key payload; it must reject the count before making a large allocation.
  • ⚠️ Cover mixed-type literals on one dynamic path in an explicit PREWHERE with both make_distributed_plan and enable_cascades_optimizer enabled. The new SQL test selects the greedy join optimizer and does not exercise this caller.
Missing context / blind spots
  • ⚠️ No local ClickHouse binary or configured build was available, so the findings were verified by tracing the current source. The CI helper returned no per-test results for the current targeted job; current-head execution of 05620_statistics_json_paths was not confirmed.
Final Verdict

Status: ❌ Block

Reject oversized sketch counts before allocation and cover the metadata-free Dynamic estimator path, with focused regressions for both.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Nov 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @hanfei1991 @nickitat, could you review this and add the can be tested label so CI runs? Statistics declared on a JSON column are now built for each path (typed, dynamic and in shared data) and the selectivity estimator uses them for filters on path subcolumns, which gives join reordering real estimates in #122437.

@clickhouse-gh clickhouse-gh Bot added can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 10, 2026
groeneai and others added 2 commits November 10, 2026 18:49
…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]>
Comment thread src/Storages/Statistics/Statistics.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 95bd5f0bd with master 2867d84c4 (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

11 object files changed (+120.17 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/Statistics/StatisticsUniqV2.cpp.o 94.03 KiB 139.67 KiB +45.64 KiB (+48.54%)
src/CMakeFiles/dbms.dir/Storages/Statistics/StatisticsBasic.cpp.o 165.57 KiB 198.33 KiB +32.77 KiB (+19.79%)
src/CMakeFiles/dbms.dir/Storages/Statistics/Statistics.cpp.o 415.02 KiB 434.93 KiB +19.91 KiB (+4.80%)

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

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - db892c3

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log not from this PR: CHECKSUM_DOESNT_MATCH after one replica of the 05223_replicated_sync_3_waits_for_active_replicas table mutated a part on 26.10.2.103 and the other on the new build. Only statistics.packed differs: #123950 (merged 2026-11-10) adds a sum to basic statistics. Replaying the mutations locally, its merge commit writes the new build's hash (d2f18c54...), while its first parent and this PR's own head write 26.10's (927af983...) a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the row above a fix task is created (the one above)

Session id: cron:clickhouse-maint-slot-12:20261110-234000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Upgrade check (amd_release) row of the ledger above: I opened #130674, a revert of #123950 (its merge commit 95d1955 writes different statistics.packed bytes than 26.10, its first parent 4e08dbd writes the same ones, amd_binary CI builds). A maintainer can choose the revert or a forward fix.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Update for the Upgrade check (amd_release) row of the ledger above: the revert #130674 was closed after the statistics author ruled the cross-version statistics.packed difference expected. The fixing PR is now #130760 (mine, open), which ignores that documented message in the upgrade log scan.

alexey-milovidov pushed a commit to pugachevdmitry/ClickHouse that referenced this pull request Nov 12, 2026
…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]>
@Avogar Avogar self-assigned this Nov 12, 2026
@hanfei1991 hanfei1991 self-assigned this Nov 12, 2026
@@ -518,10 +502,28 @@ bool ConditionSelectivityEstimator::extractAtomFromTree(const StorageMetadataPtr

if (metadata)

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.

[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.

Comment thread src/Storages/Statistics/Statistics.cpp Resolved
Comment thread src/Storages/Statistics/Statistics.cpp Resolved
@hanfei1991

Copy link
Copy Markdown
Member

@groeneai please fix build

groeneai and others added 4 commits November 18, 2026 13:59
`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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in ebab13e: the arm_tidy failure came from modernize-use-nodiscard, which master enabled after this PR was opened. The 7 errors in the CI log are the only ones clang-tidy reports on the files this PR changes.

Comment thread src/Storages/StatisticsDescription.h Resolved
Comment thread src/Storages/Statistics/Statistics.h Resolved
@clickhouse-gh clickhouse-gh Bot added comp-statistics Column statistics: statistics kept per part on a column (tdigest, uniq, count-min sketch, minmax)... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 19, 2026
groeneai and others added 2 commits November 20, 2026 00:14
…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 rschu1ze left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed, I'll cut it down to basic and uniq_v2 on JSON columns, each keeping its state per path inside StatisticsBasic and StatisticsUniqV2.

Removed: StatisticsJSONPaths and the JSONPaths type (so the mask-bit question from the earlier review goes away), the other statistics types on paths, uniq / uniq_v2 on top-level Dynamic, the per-query path projection and lazy deserialization in IMergeTreeDataPart, and the .null handling for paths.

Outside the two statistics I keep only what makes them used: loading the statistics of j when a query reads j.<path>, the estimator's lookup of j.<path>, and estimating a Dynamic path by equality only (two literals of different types on one path would otherwise throw at planning).

I'll link the commit here.

groeneai and others added 2 commits November 20, 2026 12:05
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in 0556d90 (and 95bd5f0 for two review findings): the PR is now +401/-16 in 12 files instead of +692/-37 in 17. basic and uniq_v2 keep the state of each path inside StatisticsBasic and StatisticsUniqV2, and everything listed above is removed. The description now lists what is not covered, including IS NULL on a Nullable typed path when it is rewritten to <path>.null.

String path;
readStringBinary(path, buf);
auto path_stats = std::make_shared<StatisticsUniqV2>(stat, StatisticsUtils::getJSONPathType(*json_type, path));
path_stats->deserialize(buf, version);

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] 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

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-statistics Column statistics: statistics kept per part on a column (tdigest, uniq, count-min sketch, minmax)... pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Statistics creation on JSON columns

4 participants