Skip to content

Deduplicate the LowCardinality/Nullable unwrap in monotonicity analysis - #113458

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/dedup-lowcardinality-nullable-unwrap
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/dedup-lowcardinality-nullable-unwrap

Conversation

@groeneai

@groeneai groeneai commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112339

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

...

Description

No behaviour change. This is the deduplication @PedroTadim and @Ergus both asked for on #112339,
which merged before I could apply it.

Four key-analysis sites open with the same prologue: walk a const IDataType & through a
LowCardinality wrapper, then a Nullable wrapper, by raw pointer, in that order.
src/DataTypes/ exposed that unwrap only in DataTypePtr form, and
IFunction::getMonotonicityForRange receives a reference while IDataType::getPtr() throws for a
type not owned by a shared_ptr - so those callers could not use removeLowCardinalityAndNullable
and copied the walk instead. I add the missing raw-pointer overload beside it and convert
FunctionBinaryArithmetic.h:3841, negate.cpp:43, IFunctionCustomWeek.h:47 and
IFunctionDateOrDateTime.h:129.

Correcting my earlier count in that thread: there are 4 copies under src/Functions, not 2, and 8 in
src/. I had missed the two IFunction* headers because they spell the casts
checkAndGetDataType, which is a one-line alias for typeid_cast (FunctionHelpers.h:26-29).

Four carriers are deliberately left alone: KeyCondition.cpp:1789 and :2843 (hottest file in key
analysis, several open PRs touching it), SetUtils.cpp:34 (holds a DataTypePtr and can just call
the existing function - a separate cleanup), and PNGSerializer.cpp:73 (#112846 rewrites that file,
and its removeLowCardinalityType half is also used alone at :93).

As stated in that thread, the test after the prologue stays different per site.
isCompoundForMonotonicity asks isArray || isTuple || isMap; negate.cpp:54 asks
!isValueRepresentedByNumber(). Those are not complements - DataTypeNullable has no override and
the default is false - and 04652_compound_key_monotonicity.sql:219-224 pins why unifying them is
wrong: a String key with + INTERVAL 1 DAY prunes today.

Only the first site was pinned against a silent regression, so this adds
04747_unwrap_monotonicity_dedup. Six mutants each fail it 20 of 20 randomized runs; it passes on
unmodified master, as a characterization test should.

Mutation matrix and the randomization pins

Each arm is a separate build; deterministic is --no-random-settings, randomized 20 runs with
randomization on.

arm mutation deterministic randomized
fix (this change) OK 20 OK / 0 FAIL
base pristine OK 20 OK / 0 FAIL
M1 swap the helper's strips FAIL 0 OK / 20 FAIL
M2 drop the Nullable strip FAIL 0 OK / 20 FAIL
M3 drop the LowCardinality strip FAIL 0 OK / 20 FAIL
M4 negate.cpp: force the recovered is_nullable false FAIL 0 OK / 20 FAIL
M5 revert IFunctionCustomWeek.h's unwrap FAIL 0 OK / 20 FAIL
M6 revert IFunctionDateOrDateTime.h's unwrap FAIL 0 OK / 20 FAIL

M4 is the interesting one: under it the two negate ... ORDER BY rows return empty where the Log
oracle returns the five expected values, so that arm catches wrong results, not lost pruning.

Two settings are pinned per query. optimize_read_in_order is randomized 0/1, and at 0 the sort
optimization that is the only observable of the negate verdict is off - which made M4 pass 10/10
before the pin. use_lightweight_primary_key_index_analysis is randomized with p=0.6, and at 0 the
index analysis hands the transform a key type that recursiveRemoveLowCardinality already stripped
(KeyCondition.cpp:5532), where the sparse branch passes it raw (:5973) - so a mutant breaking
only the LowCardinality half of the unwrap is invisible there. Hence the two LowCardinality-half
mutants are exactly the ones that under-reddened: M1 13/20, M3 6/20 before the pin. Both settings
read identical values on unmodified code, so the pins remove an escape hatch rather than weaken an
assertion.

Rows that cannot move either way are labelled controls in the file: LowCardinality delegates
isValueRepresentedByNumber to its dictionary, and toStartOfMonth has a ZeroTransform factor, so
it returns before the unwrap.


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

Four key-analysis sites open with the same six-line prologue: walk a
`const IDataType &` through a `LowCardinality` wrapper, then through a
`Nullable` wrapper, by raw pointer, using `typeid_cast`, in that order.
Two reviewers pointed at it independently on ClickHouse#112339.

The duplication exists because `src/DataTypes/` exposed the unwrap only in
`DataTypePtr` form. `IFunction::getMonotonicityForRange` receives a
reference, and `IDataType::getPtr()` is `shared_from_this()`, which throws
for a type not owned by a `shared_ptr`, so those callers could not reach
`removeLowCardinalityAndNullable` and open-coded the walk instead. This
adds the missing raw-pointer overload beside the existing one and converts
the four `src/Functions` copies.

`negate` read the nullability of the original type mid-walk, which the
helper does not expose. It is recovered without a second walk as
`isNullable() || isLowCardinalityNullable()`; `DataTypeLowCardinality`
reports the former as false and delegates the latter to its dictionary, so
the two spellings agree on all four wrapper shapes.

No behaviour change. Two of the four converted sites spelled the casts as
`checkAndGetDataType`, which is a one-line alias for `typeid_cast`. A
deferred carrier, `KeyCondition.cpp:2847`, spells the second strip as
`isNullable()` plus `static_cast`, equivalent because
`DataTypeNullable::isNullable()` is a `final` `true`; that will matter when
that site is converted.

Coverage: only the `FunctionBinaryArithmetic` site was pinned, by
`04652_compound_key_monotonicity`. No stateless test combined a
`negate`/`toDayOfWeek`/date-transform key with a `LowCardinality` or
`Nullable` wrapper and asserted pruning, so a wrong unwrap at the other
three landed green. `04747_unwrap_monotonicity_dedup` adds that pin. Six
mutants (swap the strips, drop either strip, hard-`false` the recovered
`is_nullable`, revert either header's unwrap) each fail it 20 out of 20
randomized runs, and it passes on unmodified master, as a characterization
test should.

Two settings are pinned per query rather than jointly. Half of all runs
draw `optimize_read_in_order = 0`, which disables the sort optimization
that is the only observable of the `negate` verdict. And 40 percent draw
`use_lightweight_primary_key_index_analysis = 0`, where the index analysis
hands the transform a key type that `recursiveRemoveLowCardinality` has
already stripped (`KeyCondition.cpp:5532`); the sparse branch passes it raw
(`:5973`). Both branches consult the transform's monotonicity, but only the
raw one can observe a wrong unwrap of the `LowCardinality` half, which is
why the two `LowCardinality`-half mutants were the ones that under-reddened
before the pin. Both settings read identical values on unmodified code, so
they remove an escape hatch rather than weaken an assertion.
@groeneai

groeneai commented Aug 5, 2026

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

Pre-publication review by an independent model (engine: codex; 0 findings across two passes;
one full cold pass, one fix round, one delta recheck). All findings below came from my own cold
review of the resulting code, written before reading the implementation notes. The fix round was
text only: git diff <base>..HEAD -- src/ is byte-identical before and after it, and the
.reference diff is empty.

# Sev Finding Verdict Evidence / action
1 ⚠️ The stated reason for pinning use_lightweight_primary_key_index_analysis was false: it said the other index-analysis branch reaches the same granule counts without consulting the transform's monotonicity AGREE, fixed @ 1506ca1 Both branches consult it unconditionally: applyMonotonicFunctionsChainToRange calls getMonotonicityForRange at KeyCondition.cpp:5021, reached from :5529 (non-sparse) and :5970 (sparse). What differs is the type argument, recursiveRemoveLowCardinality(...) at :5532 vs the raw type at :5973, and recursiveRemoveLowCardinality strips LowCardinality but re-wraps Nullable (DataTypeLowCardinalityHelpers.cpp:38-45, :89-90). So only the LowCardinality half of the unwrap is unobservable at lwpk = 0, which is why exactly the two LowCardinality-half mutants under-reddened. Corrected in the description, the commit message and the test comment. The pin itself is correct and stays; no assertion, granule count or setting changed
2 ⚠️ Four of six "near-miss" citations did not resolve on master, and that census was not reproducible under any predicate AGREE, fixed @ 1506ca1 Sentence deleted. The load-bearing counts survive and reproduce on an independent census of the base tree (8487 files under src/): 8 structural carriers, 4 of them under src/Functions. The four non-carriers among the candidates are LikePerfectAffixRewritePass.cpp (two independent predicate helpers), convertFieldToType.cpp (recursive dispatch) and ArrowIPCBlockInputFormat.cpp (recursive type rebuild)
3 💡 The commit message attributed an isNullable() plus static_cast spelling to a converted site AGREE, fixed @ 1506ca1 grep -cE 'static_cast<const DataTypeNullable' is 0 at all four converted sites; that spelling is at KeyCondition.cpp:2847, a deferred carrier. Re-attributed there, and the equivalence argument is kept because DataTypeNullable is final with isNullable() returning true
4 💡 Three files' DataTypeNullable.h include now has no second consumer DISAGREE The DataTypeLowCardinality.h include is required at every converted site, since the new overload is declared there. Two of the three files are high-fan-out headers, so changing their include set has its own compile-time blast radius and is a separate change from this dedup. Noted, not blocking

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

Also verified by reading, at all four converted sites: typeid_cast<To*> returns nullptr
rather than throwing (typeid_cast.h:26-32) and checkAndGetDataType is a one-line alias for it
(FunctionHelpers.h:26-29), so the conversion is semantics preserving; negate's recovered
is_nullable agrees with the old mid-walk observation on all four constructible wrapper shapes,
because isNullable() is overridden in exactly two places in src/DataTypes and
isLowCardinalityNullable() in one, and Nullable(LowCardinality(T)) is not constructible;
the returned pointer's lifetime is that of the argument's wrapper chain; and the two rows the
test labels controls really are controls, since toStartOfMonth's factor transform is
ZeroTransform (DateTimeTransforms.h:319) and IFunctionDateOrDateTime.h:113 returns before
the unwrap.

Session id: cron:clickhouse-review-slot-54:20260805-110002

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? N/A as a bug repro - this is a no-behaviour-change refactor. The deterministic equivalent is a two-arm A/B plus a six-mutant matrix, all reproducible on demand: cd tests && ./clickhouse-test --binary <bin> --no-random-settings --no-random-merge-tree-settings 04747_unwrap_monotonicity_dedup.
b Root cause explained? src/DataTypes/ exposed the LowCardinality-then-Nullable unwrap only in DataTypePtr form. IFunction::getMonotonicityForRange receives a const IDataType &, and IDataType::getPtr() is shared_from_this() (IDataType.h:75), which throws for a type not owned by a shared_ptr - so those callers could not call removeLowCardinalityAndNullable and open-coded the walk instead. Measured: git grep -nE "removeNullable\(const IDataType|removeLowCardinality\(const IDataType" returns 0 hits on master, i.e. no reference or raw-pointer overload existed anywhere in src/.
c Fix matches root cause? Yes - it adds the missing raw-pointer overload, removing the reason to copy, rather than papering over any symptom. No test weakened, no tag added to dodge a failure, no bound widened, no defensive check.
d Test intent preserved / new tests added? No existing test modified. Only FunctionBinaryArithmetic.h's site was pinned (by 04652_compound_key_monotonicity); measured that zero stateless tests combined a negate/week/date-transform key with a LowCardinality or Nullable wrapper and asserted pruning, so a wrong unwrap at the other three landed green. 04747_unwrap_monotonicity_dedup adds that pin. It passes on unmodified master, as a characterization test should; its value is proven by the mutants below, not by reddening.
e Both directions demonstrated? Yes. Six mutants, each a separate build with its own Build ID, each run: swap the helper's two strips; drop the Nullable strip; drop the LowCardinality strip; force negate.cpp's recovered is_nullable false; revert IFunctionCustomWeek.h's unwrap; revert IFunctionDateOrDateTime.h's unwrap. Each fails the new test 20 of 20 randomized runs, while the fix and pristine master each pass 20 of 20. The is_nullable arm is the strongest: under it the two negate ... ORDER BY rows return empty where the Log oracle returns the five expected values, so that arm catches wrong results rather than lost pruning.
f Fix is general across code paths? The invariant was censused over all of src/: 8 structural carriers. 4 converted. 4 deliberately deferred with reasons stated in the description (KeyCondition.cpp:1789 and :2843; SetUtils.cpp:34; PNGSerializer.cpp:73). Two of the four converted sites spelled the casts checkAndGetDataType, which is a one-line alias for typeid_cast (FunctionHelpers.h:26-29) - that is why my earlier count in the review thread said 2 copies where there are 4.
g Fix generalizes across inputs (params/datatypes/wrappers)? The wrapper matrix is the subject matter. Tested LowCardinality(T), Nullable(T), LowCardinality(Nullable(T)) and plain T, for both an integer key (negate) and a Date key (toDayOfWeek, toMonth, toStartOfMonth); Nullable(Tuple(Int64, Int64)) stays pinned by 04652. The helper is deliberately NOT recursive, matching every converted site's current behaviour exactly: Nullable(LowCardinality(T)) is not constructible, and Array/Tuple/Map must not be looked through since that is the value being classified.
h Backward compatible? (maintainer-approved exception only) Yes, trivially - no behaviour change, no setting, no default, no serialization format, so no SettingsChangesHistory.cpp entry is owed. The new symbol goes in DataTypeLowCardinality.h, which all four converted files already include (verified 1 hit each), so no include was added to any high-fan-out header.
i Invariants and contracts preserved? The unwrap order (LowCardinality, then Nullable) is preserved at all four sites. Lifetime: getDictionaryType() and getNestedType() both return const DataTypePtr & to a member, so the returned raw pointer is valid as long as the argument's wrapper chain is - the same guarantee all eight existing copies already relied on, stated in the helper's doc comment. The one piece of observable state the extraction could have dropped is negate's mid-walk is_nullable, used for the negate(NULL) ordering rule; it is recovered as isNullable() || isLowCardinalityNullable(), which agrees with the old observation on all four wrapper shapes (DataTypeNullable::isNullable() is final true; DataTypeLowCardinality reports it false and delegates isLowCardinalityNullable() to its dictionary), and it is pinned by the mutant above. No concurrency, error paths or early returns affected.

Session id: cron:clickhouse-review-slot-54:20260805-110002

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 5, 2026
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @rschu1ze, could you review this? It adds a raw-pointer overload of removeLowCardinalityAndNullable so the four getMonotonicityForRange sites that hold a const IDataType & can stop open-coding the LowCardinality-then-Nullable walk, which is the deduplication asked for on #112339. No behaviour change; the only subtle part is that negate read the nullability mid-walk and now recovers it as isNullable() || isLowCardinalityNullable().

@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [21bebbe]

Summary: ❌

job_name test_name status info comment
Docker server image FAIL
clickhouse/clickhouse-server:head-distroless-arm64 FAIL cidb
Docker keeper image FAIL
clickhouse/clickhouse-keeper:head-distroless-arm64 FAIL cidb
Stress test (arm_release) FAIL
Hung check failed, possible deadlock found FAIL cidb

AI Review

Summary

This PR adds a raw-pointer overload of removeLowCardinalityAndNullable, replaces four open-coded LowCardinality/Nullable unwraps in monotonicity analysis, and adds focused stateless coverage for the affected negate, week, and date transform paths. I did not find a correctness, safety, compatibility, or evidence gap in the current diff.

Final Verdict

✅ No review findings.

LLVM Coverage Report

Measured on commit 21bebbe.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 19/19 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 5, 2026
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1506ca1

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
Build (arm_release) / Post Hooks infra: build_profile_hook telemetry INSERT rejected by the CI logs cluster (LogCluster query failed with code 500), non-gating #113409 (external, open)

Notes on the one line above, since it is easy to misread as green:

  • It is invisible to the check-runs API. The enclosing Build (arm_release) check-run reports
    success and result_pr.json reports top-level OK; only the per-test row is FAIL. I
    enumerate test_status IN ('FAIL','ERROR') separately from check_status IN ('failure','error')
    for exactly this reason.
  • I read the mode off this job's own log rather than inferring it: WARNING: LogCluster query failed with code 500, then ERROR: Failed to query LogCluster, raised through
    build_profile_hook.py:293 check. Retry the build-profile telemetry INSERT through the CI logs cluster memory-pressure spikes #113409 patches that path in
    ci/jobs/scripts/log_cluster.py, rewinding the request body and retrying 5xx with a backoff.
  • The fix is not in this build: the marker string Retry the build-profile telemetry INSERT through the CI logs cluster memory-pressure spikes #113409 adds to log_cluster.py is absent at
    1506ca16acdb and present at refs/pull/113409/head, so this build predates it. Nothing is
    owed on this branch.
  • Post Hooks on this commit is 64 OK against this 1 FAIL, i.e. release-build only.

Nothing here is attributable to this PR's diff, which touches src/DataTypes/DataTypeLowCardinality.*,
four files under src/Functions/, and one stateless test. No other check failed.

Session id: cron:our-pr-ci-monitor:20260805-180000

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-datatype-wrapper Type modifiers/wrappers (Nullable, LowCardinality, etc.). label Sep 4, 2026
Every `DROP TABLE IF EXISTS` in `04747_unwrap_monotonicity_dedup.sql`
carried `SETTINGS ignore_drop_queries_probability = 0`. The setting
defaults to 0 and only two jobs ever set it - the stress test (0.2) and
the upgrade check (1, via `--fake-drop`) - and neither compares a
stateless test's per-test output, so the clause cannot affect any job
that checks results.

@ alexey-milovidov asked for these pins to be removed (ClickHouse#112005), and
ClickHouse#113117 has since deleted every one of them from master. Keeping them
on this branch would re-add a setting a maintainer has just removed.

The removal is textually exact: the file is byte-identical to its
previous content with only the trailing clause dropped from the 20
`DROP` lines, and the `.reference` is untouched because this test does
not use `-- { echo }`.
@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 21bebbecc with master 49caba0cb (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.

Compile time of recompiled translation units

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

Job report

@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 21bebbe

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
Docker server image / clickhouse-server:head-distroless-arm64 apt index fetch fails on the arm64 leg, and the buildx retry ladder rewrites the mirror error so the Canonical fallback never fires #118023 (mine, open)
Docker keeper image / clickhouse-keeper:head-distroless-arm64 same apt-mirror class as the row above #118023 (mine, open)
Stress test (arm_release) / Hung check failed, possible deadlock found a fuzzer table-function query is parked in QueryAnalyzer::resolveTableFunction (TableFunctionRemote::parseArguments); the report keeps only the last 32 KiB of hung_check.log, so the hung leaf is not measurable from CI #113428 (mine, open)

Mergeable Check and PR are rollups of the rows above, not separate failures.

Session id: cron:our-pr-ci-monitor:20260905-060038

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-datatype-wrapper Type modifiers/wrappers (Nullable, LowCardinality, etc.). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants