Skip to content

Validate a JSON subcolumn by its substream path in skip-index analysis - #119641

Open
groeneai wants to merge 13 commits into
ClickHouse:masterfrom
groeneai:fix-json-path-shadowed-by-physical-column
Open

groeneai wants to merge 13 commits into
ClickHouse:masterfrom
groeneai:fix-json-path-shadowed-by-physical-column

Conversation

@groeneai

@groeneai groeneai commented Sep 12, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #119592
Related: #119321

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed wrong results when a JSONAllPaths or JSONAllValues skip index was consulted for a name that is not a path of its JSON column. Dots are legal in column names, so a physical column named `j.some.path` can sit beside a JSON column j; index analysis read it as a path of j and skipped the granule holding the matching row. A Tuple element or dynamic path claiming that name, and a subcolumn reading a derived property such as .size0 or .null, had the same effect.

Description

A name shaped j.<rest> was taken to be a path of the index's JSON column on a string prefix split alone, nothing checked against the table's columns. Rendered subcolumn names are flat and cannot carry that question. At defaults:

CREATE TABLE jp (j JSON, `j.some.path` String,
    INDEX idx JSONAllPaths(j) TYPE text(tokenizer = splitByNonAlpha) GRANULARITY 1)
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO jp VALUES ('{"other":"v"}', 'hello');

SELECT count() FROM jp WHERE `j.some.path` = 'hello'; -- 0, wrong
SELECT count() FROM jp WHERE `j.some.path` = 'hello' SETTINGS use_skip_indexes = 0; -- 1

Both names are now resolved through ColumnsDescription, the resolver the analyzer uses; the match is refused unless the candidate is the same storage column, reached by JSON path steps and then only by descents that still read the value stored there. A length or a null map is not such a descent: JSONAllValues never holds a length, and a null map is 1 where the path is absent.

That also answers the issue's second face: with two JSON columns the shorter owns the name, the storage columns differ, and the index is not consulted. The five index types able to carry such an index share three condition classes and one matcher; each of the five was measured 0 before and 1 after. Genuine paths keep their index and prune exactly as before.

The new parameter is not a second columns_shadowing_map_subcolumns (Map key shadowing, not path ownership). My #119591 adds a same-named metadata_snapshot member to these three classes, so whichever lands second folds one member.

Complements #119321 (merged), which fixes the declared-typed-path family (#117938): this change only refuses matches, never adds one and never changes the path probed.


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

groeneai and others added 9 commits September 12, 2026 03:29
A column may legally be named `j.some.path` while the table also holds a JSON
column `j`. `tryMatchJSONSubcolumnToIndex` decided "this name is a path of that
index's JSON column" purely from the rendered string: it scanned the index
expression names for `JSONAllPaths(X)` / `JSONAllValues(X)` and, if the
candidate name started with `X` followed by a dot, declared the remainder to be
a path of `X`. Nothing checked that the name actually resolves to a subcolumn
reached through `X`, so a predicate on the physical column was answered from the
JSON path set, the path was absent, and the granule holding the matching row was
pruned. Wrong results, silently, on every index type that uses this helper
(text, tokenbf_v1, ngrambf_v1, sparse_grams, bloom_filter) and every predicate
route.

The string is irreducibly ambiguous: subcolumn names are flat and the wrapper
substreams contribute nothing to a rendered name, so `x.j.p` is the same string
whether it means Tuple element `j.p` or Tuple element `j` then JSON path `p`.
Only the serialization substream path separates them.

Resolve both the index's JSON column and the candidate name through the table
metadata - the same resolver the analyzer uses, so index analysis and the read
agree by construction - and accept the name only when it resolves to a subcolumn
of the same storage column whose substream path extends the JSON column's by
JSON path steps alone. The path is then read off that resolution instead of the
name, which also fixes subcolumns of a path (`j.a.size0`, `j.a.:`String`.null`)
whose textual remainder is not a path at all.

Resolution is two-stage, in the resolver's own order (exact column and static
subcolumn lookups first, a dynamic root only after), and its dynamic stage walks
the declared columns rather than the name's dot splits: a name can embed a
folded constant, and index analysis runs before any data is read and observes no
cancellation, so its cost must stay bounded by the schema.

The check runs per candidate inside the selection loop, not after it: one index
may carry several JSON columns, and rejecting the shortest textual match must
not discard a longer candidate that is a genuine ancestor.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ly the selected index column

A JSON skip index is matched against a filter column name in two steps, and both used to trust the
rendered string. The path a name denotes now comes from the substream path rather than from the name,
so a subcolumn OF a path no longer contributes its own name to the searched path.

Which substream tails may follow the path is a property of what the two index contents hold, not of
the object serialization, so the rule moves out of SerializationObject and becomes a closed
allow-list of value-preserving descents: an element that reads a stored value under the path is
allowed, an element that reads a property derived from it is not. A size is never among the values
JSONAllValues holds, and a null map is 1 exactly where the path is absent, which is the opposite of
what the path set models; both are refused, both returned wrong results before. The list is closed
rather than a list of exclusions so that an unclassified substream type refuses by default.

Only the index column the textual scan selects is validated, and a longer entry that also owns the
name is not tried in its place: probing that one asks it for the path the name denotes inside it, and
JSONAllPaths emits only the first element of a path that continues into a nested object, which prunes
the granule holding the match. Keeping master's selection also makes the change monotone, since the
index column probed is always the one that was probed before.

resolveName walks the schema once instead of restarting the scan per dot-prefix. Index analysis runs
before any data is read and observes no cancellation, so its cost must stay bounded by the schema
rather than by a name that can embed a folded constant.

Co-Authored-By: Claude Opus 5 <[email protected]>
05190 covers a physical column whose name shadows a JSON path and its subcolumns, a name claimed
inside a Tuple element, the derived-property tails that must not be answered from either index, and
the structural descents under a typed composite path whose searched path this change corrects. The
control arms assert the plan as well as the count, because a count alone also passes when the index is
absent from the plan, which is what a too-broad guard causes.

Arms 1-3 are one per index condition class rather than one per index type, since tokenbf_v1 and
sparse_grams share a condition class with ngrambf_v1.

04780 gains a fifth arm for the one shape that reaches metadata resolution through a dot-dense name, a
genuine JSON subcolumn reference. Its control is the same query on a table with no JSONAllPaths index,
so parsing and analysis are identical and only the matching differs; a control of equal character
length but a single path element measures the parser's per-part cost, which is 1.57x and unrelated.

Co-Authored-By: Claude Opus 5 <[email protected]>
Reading the null map of an absent JSON path yields 0 under the `advanced` shared data serialization
and 1 under `map`. The test runner randomizes that setting, so the arm asserting that a null map tail
is not answered from the path set failed in 10 of 50 runs while measuring the reader rather than the
rule it exists for. Pinning it on that one table keeps the arm deterministic; the other arms are
unaffected by the setting, so nothing else is pinned.

Co-Authored-By: Claude Opus 5 <[email protected]>
The path is read off the rendered subcolumn name again, as it was before. What this change keeps is
the pair of refusals: a name is matched to a `JSONAllPaths` or `JSONAllValues` index only when the
table metadata resolves it to a subcolumn of the same storage column as the index's JSON column,
reached from that column by JSON path steps, and whose remaining tail still reads the value stored at
that path. Otherwise the index is not consulted for that predicate, which costs pruning and nothing
else.

Correcting the path as well does fix a subcolumn inside a declared typed path, but ClickHouse#119321 fixes that
family by refusing it, and recognises it by finding a declared typed path in the prefix of the derived
path. A corrected path has no such prefix, so a tree containing both changes would lose that refusal
in either merge order. Leaving the derivation alone keeps the two changes independent: this one can
only decline a match that would otherwise be made, and asks for the same path when it does match.

The test arms that asserted the corrected paths go with it.

Co-Authored-By: Claude Opus 5 <[email protected]>
…wed-by-physical-column

Four conflicts, all in the same place and all additive: master now passes a
`NameSet columns_shadowing_map_subcolumns_` to `MergeTreeIndexConditionBloomFilter`,
`MergeTreeConditionBloomFilterText` and `MergeTreeIndexConditionText`, and this branch
passes them a `StorageMetadataPtr metadata_snapshot_`. Both are kept, in the same order in
all three classes: `metadata_snapshot_` directly after `context_`, the `NameSet` last.

Files: MergeTreeIndexBloomFilter.{h,cpp}, MergeTreeIndexBloomFilterText.cpp,
MergeTreeIndexText.cpp. MergeTreeIndexJSONSubcolumnHelper.{h,cpp} is untouched by the merge.
The 2000-dot arm of `04780` has a one-sided oracle: it fires only when the resolved arm allocates
more than 150% of its control, so a change that stopped matching the long name at all would lower
the measurement and pass. That arm exists to guard against an uncancellable planning walk, so it
now also asserts that the long name is still matched and its granules still pruned. The assertion
is identical before and after this change by design: it is a liveness guard, not a fix detector.

The three index condition classes now take two parameters derived from the same metadata snapshot.
`columns_shadowing_map_subcolumns` is a precomputed set answering whether a name is a column that
shadows a `Map` key subcolumn; the snapshot answers on demand whether a name resolves to a path of
this `JSON` column. Different data, different question, and neither reads the other's.

`05190` gains two arms. `isNotNull` reaches the matcher from two condition classes no other arm
covers, and only with `optimize_functions_to_subcolumns` off, because the rewrite turns the
function into a null-map read before index analysis sees it; its claimant is `Nullable` because the
route early-outs on a non-Nullable argument. A typed path under `JSONAllValues` is the one
typed-path shape whose granules can be pruned, since `JSONAllPaths` emits a non-Nullable typed path
for every row and the `JSONAllPaths` typed-path arms can therefore only assert index eligibility.

The dynamic stage of `resolveName` walks the declared columns rather than the name's dot splits,
which is what `ColumnsDescription::tryGetColumn` does once dynamic subcolumns are enabled. Both
reach the same root, the shortest declared prefix that owns the remainder, but a name can embed a
folded constant, so splitting it costs O(length^2) allocated bytes, and index analysis runs before
any data is read and observes no cancellation.
Issue 119592 reports this defect with two shapes the file did not carry.
Face 1 indexes a JSON column whose own name contains a dot (`j.a` JSON
beside a physical `j.a.b` String), which additionally exercises the scan's
handling of a dotted index-column name; both names are declared, so the
resolver answers at its first stage and the ownership check refuses on
`name_in_storage`. Face 2 declares two JSON columns where the shorter one
owns the name (`j` and `j.a`, index on `JSONAllPaths(j.a)`): the resolver
sorts candidate roots shortest-first and binds `j.a.b` to `j`, so the
index's column is not the name's owner and the check refuses again. The
reporter's own `toTypeName(j.a.b)` of `Dynamic` is what that binding looks
like from SQL, and it holds on both binaries.

Measured on the unfixed binary before the arms were written: each indexed
count is 0 while its `use_skip_indexes = 0` oracle is 1, so both shapes are
this defect and not a coincidence of the fixture. Arm 22 is the first arm in
the file whose answer depends on the root order at all, because every other
shape resolves with at most one candidate root: the physical-column arms
answer at the resolver's first stage, and the arms with two JSON-typed names
declare them inside a single top-level Tuple, which the root loop does not
descend into. Reversing the sort predicate reddens arm 22 and nothing else,
so the order is asserted rather than assumed.

Both arms measure a refusal, so per the file's own convention they assert
the count only and each carries its unindexed oracle line.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Sep 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Three review rounds before this PR was opened: pre-publication review by an independent model
(engine: codex; 3 findings over two gated rounds) plus my own cold reviews of the resulting code
(11 findings over three rounds). Two rounds of fixes were sent back and executed.

# Sev Finding Verdict Evidence / action
1 ❌ The validated JSONAllValues route still prunes true rows when a missing path or map key yields the compared type's default, e.g. j.missing::UInt64 = 0 returning 0 indexed against 1 unindexed DISAGREE both names are a genuine path or descent of j, so master accepted them and this change still accepts them with the same probed path. Every branch this change adds returns "no match", so the accepted set can only shrink; extractPathFromSubcolumn is untouched; and the missing guard is pre-existing, not removed here (isJSONPathFilterSafe appears nowhere in this file on master, and the equality construction cited is not in the diff). Out of scope: the changelog scopes this fix to a name that is not a path of its JSON column, while default-value safety on a genuine path belongs to isJSONPathFilterSafe
2 ❌ The branch no longer merged into master: #119457 had landed and added a parameter to the same three condition-class constructors AGREE, fixed merged master, both parameters kept side by side; they answer different questions and read different data
3 ❌ Neither face of the reported issue had been run on either binary, yet the body carried Closes: AGREE, fixed both faces measured on two Build-ID-asserted binaries: 0 before, 1 after, oracle 1 on both. Arms 21 and 22 added
4 ⚠️ The resolver's shortest-first root ordering had no oracle: reverse it and a granule holding a match is pruned silently AGREE, fixed arm 22 is the only shape where two top-level columns can own the name; a local mutation reversing the sort predicate reddens exactly that arm and nothing else
5 ⚠️ 04780's new 2000-dot arm passes if the matcher simply declines the long name, so it does not prove the resolver it measures is still live AGREE, fixed the arm now also asserts that the long name is matched and the index consulted, and a local mutation removing the resolution makes that assertion fail
6 ⚠️ The draft promised that genuine declared typed paths keep "their pruning", but a non-Nullable typed path is emitted by JSONAllPaths for every row, so those controls can only assert index eligibility AGREE, fixed src/Functions/JSONPaths.cpp skips typed paths only when NULL; the claim is narrowed to what is shown, and a typed-path control under JSONAllValues, which can prune, was added
7 ⚠️ The description said "all four affected index types"; there are five, over three condition classes AGREE, fixed tokenbf_v1, ngrambf_v1 and sparse_grams all register to the same creator, so the count was wrong even though the measurement was not
8 ⚠️ Nothing said why the new parameter coexists with the columns_shadowing_map_subcolumns set the same constructors already take AGREE, fixed stated in the description and the commit message; #119457's mechanism is deliberately left alone
9 ⚠️ Nothing warned that #119591, also mine, adds an identically named metadata_snapshot member to these same three condition classes AGREE, fixed one clause added: whichever of the two lands second folds one member rather than adding two
10 💡 resolveName's doc comment narrated a rejected alternative and another file's internals, and duplicated the comment three lines below it AGREE, fixed moved to the commit message
11 💡 No test arm covered the isNotNull route, which is a separate call site AGREE, fixed one arm added on a Nullable claimant
12 💡 Four doc comments exceed my usual per-block length limit DISAGREE each states why a non-obvious property holds (a length is never a stored value; a null map is 1 exactly where the path is absent; a registered static subcolumn outranks a shorter dynamic root), which is the class I keep rather than trim; the whole change adds 177 code lines to 44 comment lines
13 💡 The reversed-declaration-order arm asserts 0 against 0 and looks vacuous DISAGREE it pins index/no-index agreement, so a future divergence prints 1 against 0 and fails it; that is what its header says it is for
14 💡 The null-snapshot guard is unreachable, since the existing shadowing helper dereferences the same snapshot unconditionally DISAGREE unreachable but fail-safe: an empty column list refuses every match, which cannot drop rows

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

One correction to the issue's own census: the first shape listed there as unaffected,
hasToken(`j.a.b`, 'hello'), is in fact affected. Measured on the unfixed binary it returns 0
against an oracle of 1, and EXPLAIN indexes = 1 shows the index consulted and both granules
pruned. It is fixed by this change as well; it needs no separate arm, since the arm on
hasAnyTokens already covers that condition class.

Also noticed and deliberately not raised, both identical before and after this change and so not
this PR's to fix: a JSONAllValues text index tokenizes each value with its nested serializeText
while the compared constant is textualised separately, so a value whose two encodings differ can
miss its n-grams; and the JSONAllValues route in MergeTreeIndexConditionText never consults
isJSONPathFilterSafe, so a genuine but absent path compared against its type's default can still
prune the granule that matches. I make no claim about either here.

Session id: cron:clickhouse-review-self-slot-58:20260912-154000

@clickhouse-gh clickhouse-gh Bot closed this Sep 12, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The CREATE/INSERT/SELECT block in the description, single row, default settings, no forced index: 0 with the index, 1 with use_skip_indexes = 0, 100% of runs.
b Root cause explained? Yes. A rendered subcolumn name was split by string prefix to decide whose name it is. Rendered names are flat (ObjectData, ObjectStructure, ArrayElements and NullableElements contribute nothing), so x.j.p is one string for two different columns; only the substream path separates them.
c Fix matches root cause? Yes. Identity is resolved through ColumnsDescription, the resolver the analyzer itself uses, so index analysis and the read agree by construction. No widened bound, no no-random-* tag, no guard at the symptom site: an unresolvable name simply loses the index, which reads the granule and is always correct.
d Test intent preserved / new tests added? New 05190_json_path_shadowed_by_physical_column (21 arms: one per condition class, both matchers, =/IN/hasAnyTokens/isNotNull, the four claimant kinds, the two derived-property tails, both faces of the reported issue, and eight controls asserting the plan two-sided) plus a fifth arm in 04780_json_subcolumn_index_match_not_quadratic, whose one-sided allocation oracle now also asserts that the long name is still matched and its granules still pruned. 04024_json_skip_index_* and 04062_text_index_json_all_values_ghdata pass with no edit.
e Both directions demonstrated? Yes. Repro 0/1 before, 1/1 after, on two Build-ID-asserted binaries. 05190 is red on the unfixed binary in exactly 14 lines (every refusal arm, no control) and green on the fixed one, and each refusal arm carries its use_skip_indexes = 0 oracle, which reads 1 on both. 50/50 randomized runs pass.
f Fix is general across code paths? Yes. All three condition classes (text; ngrambf_v1, tokenbf_v1 and sparse_grams through MergeTreeConditionBloomFilterText; bloom_filter), both matcher families, the =/IN/hasAnyTokens/LIKE/isNotNull routes and the CAST-unwrapping retry all funnel through the single gated function, so the fix is at the source rather than at eight call sites.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured on Nullable(JSON), Array(JSON), Variant, Tuple, Map and the map key/value projections; static and dynamic paths; nested paths under a Tuple element; the .:`Type` hint and the [] flatten sugar; .size, .size0 and .null tails; both declaration orders; multi-JSON-column indexes; object_serialization_version v1/v2/v3 and all three shared-data versions.
h Backward compatible? (maintainer-approved exception only) Yes. No setting is added or re-defaulted, so no SettingsChangesHistory.cpp entry; no index format, serialization or on-disk change. The only behavioural change is that some predicates stop using an index, which cannot change a result.
i Invariants and contracts preserved? Yes. The matcher's contract is unchanged: std::nullopt already meant "do not use the index for this predicate" for ^/@ names. Acceptance only ever shrinks and an accepted name is probed with the same path as before, verified over 24 shapes. The O(index_columns) matching bound of 14220c5a7b4cf is preserved and measured by the cost test (1.0037x against its 150% threshold, unchanged). Nothing is persisted, so there is no crash or restart re-entry path.

Session id: cron:clickhouse-impl-self-slot-57:20260912-145600

@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0b7a53b]

Summary: ✅


AI Review

Summary

This PR hardens JSON skip-index matching by resolving candidate subcolumns through ColumnsDescription and refusing shadowed or derived names, which fixes the wrong-result cases from #119592. However, the matcher still stops at the first textual prefix before it checks which indexed JSON column actually owns the name, so a genuine path can still lose skip-index pruning when the real owner is a later indexed JSON subcolumn. Because that breaks the PR's own "genuine paths keep their index" contract, I do not think the change is ready to merge yet.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeIndexJSONSubcolumnHelper.cpp:277] tryMatchJSONSubcolumnToIndex commits to the shortest textual match and returns nullopt as soon as that candidate fails ownership validation. That is still wrong for shapes such as x Tuple(j JSON, \j.p` JSON(a UInt64))with an index on(JSONAllPaths(x.j), JSONAllPaths(x.`j.p`)): for x.`j.p`.a = 42, the shorter candidate x.jdoes not own the filter column, but the later indexed columnx.`j.p`does, and probingJSONAllPaths(x.`j.p`)with patha` is sound. The current early return drops that second candidate entirely, so valid skip-index pruning regresses for multi-column JSON indexes. Suggested fix: validate candidates inside the scan loop, or keep scanning after an ownership mismatch and recompute the suffix relative to each surviving candidate.
Final Verdict

⚠️ Needs changes before merge: the ownership check still rejects a real, safe multi-column JSON-index match and loses pruning on a genuine path.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @ahmadov @shankar-iyer, could you review this? A JSONAllPaths/JSONAllValues skip index decided path ownership by a string prefix split, so a physical column legally named `j.some.path` beside a JSON column j was read as a path of j and the granule holding the matching row was pruned. Both names are now resolved through ColumnsDescription, and the match is refused unless the substream path proves ownership.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0b7a53b08 with master 457f57469 (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

12 object files changed (+55.77 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexJSONSubcolumnHelper.cpp.o 64.93 KiB 115.29 KiB +50.36 KiB (+77.56%)

719 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

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

Job report

…wed-by-physical-column

# Conflicts:
#	src/Storages/MergeTree/MergeTreeIndexConditionText.cpp
Comment-only change: the comment-stripped token stream of every touched file
is byte-identical to the previous commit.

The removed text is motivation and design history, which the pull request
description already carries: why a rendered subcolumn name cannot say whose
name it is, why the probed path is still read off the rendered name, why a
longer owning index column is not re-selected, and the per-index soundness
argument for refusing derived properties. What stays is what a reader of the
code needs at each spot.
@clickhouse-gh clickhouse-gh Bot added comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Sep 27, 2026
Comment on lines +297 to +304
/// Only the selected entry is validated: a longer owner would be probed for a nested path `JSONAllPaths` never emits.
auto resolved_json_column = resolveName(columns, String(matched_json_column));
auto resolved_name = resolveName(columns, column_name);
if (!resolved_json_column || !resolved_name)
return std::nullopt;

if (!isJSONPathOfColumn(*resolved_json_column, *resolved_name))
return std::nullopt;

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.

This stops after disproving the shortest textual candidate, but a multi-column JSONAllPaths index can still have a longer indexed JSON column that really owns the name and is safe to probe.

Concrete shape:

x Tuple(j JSON, `j.p` JSON(a UInt64)),
INDEX idx (JSONAllPaths(x.j), JSONAllPaths(x.`j.p`)) TYPE bloom_filter

For x.j.p.a = 42, resolveName correctly shows that x.j does not own the filter column, but the real owner is the second indexed column x.j.p``. Returning here drops that second candidate entirely, so the query loses skip-index pruning even though probing JSONAllPaths(x.j.p`)` with path `a` is sound.

The "longer owner would be probed for a nested path" argument only holds for descendants like a.b. Once the owner switches to x.j.p``, the suffix becomes just a, which `JSONAllPaths` does emit. Can we validate candidates inside the scan loop and continue after a non-owner, recomputing the suffix relative to each candidate?

# Conflicts:
#	src/Storages/MergeTree/MergeTreeIndexText.cpp

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-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. groeneai-origin-self PR origin: self-found defect (impact-bar validated) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A JSONAllPaths skip index prunes granules for a name that resolves to a different column, silently dropping rows

2 participants