Skip to content

Lazy materialization nondeterministic defaults - #126939

Open
KochetovNicolai wants to merge 15 commits into
masterfrom
lazy-materialization-nondeterministic-defaults
Open

KochetovNicolai wants to merge 15 commits into
masterfrom
lazy-materialization-nondeterministic-defaults

Conversation

@KochetovNicolai

@KochetovNicolai KochetovNicolai commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Related: #122682
Related: #122682 (comment)

Claude

When a part does not have a column (for example, the column was added with ALTER TABLE ... ADD COLUMN after the part was written), the read fills the column from its DEFAULT. If a needed column of the default is also missing, the read fills that column from its own default too.

Lazy materialization reads some columns in a second, lazy read after LIMIT. The lazy read fills missing columns again, on its own. With a non-deterministic default, the two reads give different values for the same row. Example: n DEFAULT rand64() and s DEFAULT toString(n). The main read gives n for the filter, and the lazy read computes s from a new n. Then n = toUInt64(s) is false in the result.

This affects both lazy materialization of ORDER BY ... LIMIT (query_plan_optimize_lazy_materialization) and lazy materialization over joins (query_plan_lazy_materialization_for_join), because both use the same lazy MergeTree read.

The fix: a column is not read lazily if its DEFAULT calls a non-deterministic function, directly or through the defaults of the columns it reads. The new function getNonDeterministicDefaults in inplaceBlockConversions finds such columns. It counts a function it cannot find (such as a user-defined function) and a subquery as non-deterministic. ReadFromMergeTree::getLazilyReadColumns and ReadFromMergeTree::getLazilyReadablePositions keep these columns in the main read. Columns with deterministic defaults are still read lazily.

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):

Do not use non-deterministic table defaults for lazy column materialization. Otherwise, the result could be inconsistent.

🤖 Generated with Claude Code


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

KochetovNicolai and others added 2 commits October 20, 2026 10:48
…inistic column of the main read

For a part that lacks a column, a read fills it from its `DEFAULT`, and it fills the same way the
columns the default reads that the part lacks too. A lazy read of `MergeTree` therefore fills such
a column again from its own values of the columns its default reads. When one of them is read by
the main read and filled from a non-deterministic default, such as `s DEFAULT toString(n)` with
`n DEFAULT rand64()`, the lazy read computed `s` from another `n` than the one the query returns.

Keep such columns in the main read. Deterministic defaults give the same values in both reads, so
they are still read lazily. The check is shared by lazy materialization over joins
(`getLazilyReadablePositions`) and of `ORDER BY ... LIMIT` (`getLazilyReadColumns`).

Related: #122682 (comment)
Related: #122682

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Simplify the check: a column whose `DEFAULT` calls a non-deterministic function, itself or through
the defaults of the columns it reads, is not read lazily, whatever the main read reads. The check is
`getNonDeterministicDefaults` in `inplaceBlockConversions`, next to the evaluation of defaults.

Set `query_plan_optimize_lazy_materialization` and `query_plan_max_limit_for_lazy_materialization`
in the test, which the random settings can change so that nothing is read lazily.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bccaf31]

Summary: ✅


AI Review

Summary

Reviewed PR head bccaf318236fd82b3ac2282d4cd1c37c24b784f5. The change keeps columns filled from non-deterministic DEFAULT or MATERIALIZED expression chains in the main MergeTree read, preserving consistent values across lazy materialization for sorting and joins. The earlier findings are addressed in the current code and covered by the consolidated regression tests. No outstanding findings or new inline comments.

Missing context / blind spots
  • ⚠️ No local ClickHouse executable or build directory was available, so the regression tests were inspected but not executed here. The fetched CI report did not expose results for the two consolidated tests at this head; their completed CI results would close this validation gap.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 20, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bccaf3182 with master 57aa10da3 (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

3 object files changed (+43.65 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/inplaceBlockConversions.cpp.o 326.46 KiB 359.12 KiB +32.66 KiB (+10.01%)

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

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

Job report

KochetovNicolai and others added 2 commits October 21, 2026 14:47
…rministic defaults

Two cases of the review:

- `arrayReduce`, `arrayReduceInRanges` and `initializeAggregation` are as deterministic as the
  aggregate function their arguments name, such as an unseeded `groupArraySample`, which the overload
  resolver does not know. They count as non-deterministic.
- A default can read a subcolumn, such as `toString(n.v)`: the defaults it reads are now looked up by
  the storage column, so the non-deterministic default of `n` counts for it.

Review: #126939 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…faults

A read fills a column from its `DEFAULT` only for a part that lacks it, so the check of non-deterministic
defaults now looks only at the columns that a part to read lacks, also along the chain of defaults. It
no longer makes the functions of the defaults of stored columns, which need the privileges of the
functions: with `s String DEFAULT demangle('_Z3foov')` stored in every part, a user with only `SELECT`
could not read `s` with lazy materialization (`ACCESS_DENIED`). Where a part lacks the column, the read
itself computes the default with the same context. Tables without added columns lose no lazy reads.

Review: #126939 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…names and drops

The check of non-deterministic defaults looked at the columns of a part by their names. A part that a
pending `RENAME COLUMN` did not rewrite yet stores the column under its old name, so the check took the
column as missing and looked at its default: with `s String DEFAULT demangle('_Z3foov')` renamed, a user
with only `SELECT` got `ACCESS_DENIED` with lazy materialization. A part that a pending `DROP COLUMN` did
not rewrite yet still stores the dropped data, which the reader does not read: after `n` is dropped and
added again with `DEFAULT rand64()`, the check took `n` as stored, and a lazily read
`s DEFAULT toString(n)` was computed from another `n` than the one the query returned.

Resolve the column in each part with its `AlterConversions`, as the reader and `estimateReadBytes` do.

Review: #126939 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…e non-deterministic defaults

A part that a pending `MODIFY COLUMN` from `Nullable` did not rewrite yet stores the column as `Nullable`,
and the read fills its `NULL` values from the `DEFAULT` (`convertRequiredExpressions`). The check of
non-deterministic defaults took such a column as stored: with `n DEFAULT rand64()` and a lazily read
`s DEFAULT toString(n)`, `s` was computed from another `n` than the one the query returned.

The check of the parts is now a function of `ReadFromMergeTree.cpp`, `isFilledFromDefaultInSomePart`,
which the callers give to `getNonDeterministicDefaults` in a lambda, instead of a member that made it.

Review: #126939 (comment)
Review: #126939 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… the non-deterministic defaults

A reader fills a missing column from its `DEFAULT` with the settings of the features turned on
(`IMergeTreeReader::createContextForDefaultExpressions`), so a default works when the query has the setting
it was created with off. The check of non-deterministic defaults made the functions with the query context:
with `s String DEFAULT fuzzQuery('SELECT 1')` added under `allow_fuzz_query_functions = 1` and the setting
off again, a read with lazy materialization threw `SUPPORT_IS_DISABLED`. The check now makes them with a
copy of the context with `enableAllExperimentalSettings`, as the reader does.

A known limitation stays, noted in the code: before the analysis of ranges, the check looks at the parts
of partitions the query leaves out as well, so the default of a column missing only there can need the
privileges of its functions. Moving the privilege checks of functions from their creation to `build` closes
it.

Review: #126939 (comment)
Review: #126939 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@nickitat

Copy link
Copy Markdown
Member

🕵 Merged master into this branch and resolved the conflicts caused by #129617 (the switch to the -WithMemoryTracking containers). I also added a small commit that switches the new code to the -WithMemoryTracking types where it meets the APIs changed there, so that it compiles. This update was made automatically.

arwenizEr pushed a commit to arwenizEr/ClickHouse that referenced this pull request Nov 18, 2026
`FunctionFactory::get` / `tryGet` call the creator of a function also when
the caller only reads the properties of the function, for example
`isDeterministic`. The creators of `demangle`, `addressToSymbol`,
`addressToLine`, `addressToLineWithInlines`, `file`, `getMacro`,
`getServerSetting` and `getMergeTreeSetting` checked privileges, so such a
lookup could throw `ACCESS_DENIED` / `FUNCTION_NOT_ALLOWED`. For example,
a user with only `SELECT` could not read any column with
`apply_mutations_on_fly = 1` if a pending mutation used `demangle`,
because `AlterConversions` looks up the functions of the mutation.

Add the virtual method `checkAccessOnBuild` to `IFunctionOverloadResolver`
and `IFunction`. `IFunctionOverloadResolver::build` calls it first. Queries
build every function they use, so they fail as before.

The functions do not keep the context: `FunctionAccessCheck` keeps the
`ContextAccess` of the user and the `QueryPrivilegesInfo` of the query.
`ContextAccess` used the context only to record the checked privileges,
so a new `checkAccess` overload takes `QueryPrivilegesInfo &`, and
`QueryPrivilegesInfo` moves to its own header.

Related: ClickHouse#126939

Co-Authored-By: Claude Opus 5.5 <[email protected]>
KochetovNicolai and others added 2 commits November 18, 2026 17:46
…ed parts

Whether a column with a non-deterministic `DEFAULT` is read lazily is decided
before the analysis of ranges, so the defaults of the columns missing in parts
that the primary key leaves out are looked at as well. Since the privileges of
functions are checked in `checkAccessOnBuild` and not in their creators,
looking at a default with `FunctionFactory::tryGet` does not need them. Update
the comments and add a test with a user that has only `SELECT`.

Related: #126939 (comment)
Related: #127443

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…th `IN`

A default such as `k IN values_set` reads a set from a table, which can change
between the main read and the lazy read, while `in` reports deterministic and
its operand is not a subquery. Take an `IN` as non-deterministic unless its set
is written in the expression, as a literal or a `tuple`. The defaults that read
such a column are not read lazily as well.

Related: #126939 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

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

  • Does the same apply to MATERIALIZED columns that are absent in some parts?
  • The number of added test files seems too large compared to the change. Maybe one or two covering the main cases would be enough?

@stresshouse

stresshouse Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

no significant changes detected. K_source=4 K_base=20 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: bd4e6d99-30b9-443f-916b-7d218cee225f
  • MIRAI run: cfab11ce-d844-4a4a-9256-bac8878289e9
  • PR check IDs:
    • clickbench_551787_1795211042
    • clickbench_551793_1795211042
    • tpch_adapted_1_official_551830_1795211042
    • tpch_adapted_1_official_551851_1795211042

fm4v added 2 commits November 20, 2026 21:04
…tion into two

As asked in the review (#126939 (review)), the eight tests become two: `05839_lazy_materialization_nondeterministic_defaults` for the kinds of non-deterministic defaults (a function, an aggregate function, a subcolumn, `IN` over a `Set` table, a default with a disabled feature), and `05840_lazy_materialization_defaults_pending_mutations_and_privileges` for how the parts are looked at (pending `DROP`, `RENAME` and `MODIFY` from `Nullable`, parts the primary key leaves out, privileges). Every case is kept, and a case of `MATERIALIZED` columns is added: they are filled from their expression as `DEFAULT` ones.
@fm4v

fm4v commented Nov 20, 2026

Copy link
Copy Markdown
Member

@vdimir, answers to both questions:

  • MATERIALIZED columns are covered. getNonDeterministicDefaults takes the expressions from ColumnsDescription::getDefaults, which returns every column with an expression, whatever its kind (DEFAULT, MATERIALIZED, ALIAS, EPHEMERAL). For a part that lacks the column, the reader fills a MATERIALIZED column from its expression just as it fills a DEFAULT one, so the same check applies. I checked it on the PR CI binary: with n UInt64 MATERIALIZED rand64() and s String MATERIALIZED toString(n) added by ALTER after the insert, SELECT k, n, s FROM t ORDER BY n LIMIT 20 keeps n = toUInt64(s) for all 20 rows, and EXPLAIN shows only k read lazily. The new test now has this case. An ALIAS column is never read from a part, so lazy materialization does not see it. An EPHEMERAL column is not stored, so the read always fills it from its default.
  • Tests: in bccaf31 I merged the eight tests into two, keeping every case. 05839_lazy_materialization_nondeterministic_defaults covers the kinds of non-deterministic defaults (a function, an aggregate function, a subcolumn, IN over a Set table, a default that uses a disabled feature, and the new MATERIALIZED case). 05840_lazy_materialization_defaults_pending_mutations_and_privileges covers how the parts are checked (pending DROP, RENAME, and MODIFY from Nullable, parts that the primary key leaves out, and the privileges a default needs).

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

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-bugfix Pull request with bugfix, not backported by default v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants