Skip to content

Evaluate a DEFAULT column from the patched value of the column it reads - #118630

Open
alexey-milovidov wants to merge 56 commits into
masterfrom
fix-lwu-default-column-117023
Open

alexey-milovidov wants to merge 56 commits into
masterfrom
fix-lwu-default-column-117023

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

Closes: #117023

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

Fix a stale read after a lightweight UPDATE of a column that a DEFAULT column depends on, when neither column is stored in the data part.

Description

With a UInt32 DEFAULT 0 and z UInt32 DEFAULT a + 1000 both added by ALTER TABLE ... ADD COLUMN after the part was written, UPDATE t SET a = 5 followed by SELECT a, z returned 5, 1000, while the equivalent ALTER TABLE ... UPDATE a = 5 returns 5, 1005.

A column the part does not store comes into existence only when the missing defaults are evaluated, so a patch part can be applied to it only after that pass (ColumnForPatch::Order::AfterEvaluatingDefaults). Its dependent DEFAULT columns were computed during that pass, from the value the default gave rather than from the patched one. MergeTreeReadersChain now evaluates the defaults once more after applying the patches, for the columns that pass produced and the patches did not; the columns a patch produced keep their patched values.

The same query without the updated column in the select list (SELECT z) read no column at all: injectRequiredColumnsRecursively adds the columns a DEFAULT expression reads only when the part stores them, so the patch that supplies the value was not even selected for the read task and the expression was evaluated with the column's own default substituted into it. A column that a patch updates is now read even when the part does not store it.

Both shapes, and a chain of dependent columns, are covered by 05136_lwu_default_depends_on_missing_updated_column, which compares the lightweight UPDATE against the heavy ALTER TABLE ... UPDATE on the same data.

A mutation that is still pending is applied on the fly by a reader step of its own, and a lightweight UPDATE issued after it is applied only at the boundary of that step (applyPatchesAfterReader), after the step has evaluated its DEFAULT columns. ReadResult now carries the names of the columns whose value is still the one their DEFAULT gave; a column leaves the set when a patch overwrites it or a step's action recomputes it, and after every boundary pass that patched something the rest are evaluated again from the accumulated block (IMergeTreeReader::evaluateDefaults). The patches are also applied to the columns a mutation step projected out into additional_columns, which the last step keeps for that purpose. 05233_lwu_default_pending_mutation_later_patch covers a pending ALTER TABLE ... UPDATE plus a later lightweight UPDATE read with apply_mutations_on_fly = 1, in both select-list shapes and with a mutation that overwrites the dependent itself, and compares each on-the-fly result with the one read after the mutation has materialized.

Which rows of a DEFAULT column a patch overwrote is tracked row by row (ReadResult::rows_filled_by_defaults), so the result does not depend on the read block size: only the rows that still hold the value of the DEFAULT are evaluated again, and a dependent column with patched rows of its own is evaluated again from the combined value of the column it reads. A missing sort-key column is the exception: the rows of the part are sorted by the value its DEFAULT gave, so it keeps that value (evaluating it again would change the key without reordering the rows and break ordered reads and merges, see #129600). Whether the part stores a column follows the reader's rules for pending RENAME COLUMN and DROP COLUMN, so a column dropped by a pending mutation and added again with a new DEFAULT counts as missing. These cases are covered by 05332_lwu_default_sorting_key_column, 05394_lwu_default_partially_patched_rows, 05395_lwu_default_dependent_with_patched_rows and 05396_lwu_default_pending_drop_readd.


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

With `a UInt32 DEFAULT 0` and `z UInt32 DEFAULT a + 1000` both added by
`ALTER TABLE ... ADD COLUMN` after the part was written, `UPDATE t SET a = 5`
followed by `SELECT a, z` returned `5, 1000`, while the equivalent
`ALTER TABLE ... UPDATE a = 5` returns `5, 1005`.

A column the part does not store comes into existence only when the missing
defaults are evaluated, so a patch part can be applied to it only after that
pass. Its dependent `DEFAULT` columns were computed during that pass, from the
value the default gave rather than from the patched one. `MergeTreeReadersChain`
now evaluates the defaults once more after applying the patches, for the columns
that pass produced and the patches did not.

The same query without the updated column in the select list (`SELECT z`) read
no column at all: `injectRequiredColumnsRecursively` adds the columns a
`DEFAULT` expression reads only when the part stores them, so the patch that
supplies the value was not even selected for the read task, and the expression
was evaluated with the column's own default substituted into it. A column that
a patch updates is now read even when the part does not store it.

Closes: #117023

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

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7a583f3]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) FAIL
04891_timeseries_lowcardinality_id FAIL cidb
05033_lazy_materialization_column_function_structure_equals NOT_FAILED cidb
04353_text_index_explicit_tokenizer_argument NOT_FAILED cidb
05234_promql_result_timestamp_scale NOT_FAILED cidb
05059_promql_empty_by_group NOT_FAILED cidb
05019_group_by_top_k_compatibility NOT_FAILED cidb
03892_grouping_sets_force_aggregation_in_order NOT_FAILED cidb
04908_group_by_top_k_max_k_cap NOT_FAILED cidb
05076_promql_label_manipulation_label_names NOT_FAILED cidb
05320_promql_duplicate_series_one_to_one_matching NOT_FAILED cidb
1 more test cases not shown
Performance Comparison (arm_release, master_head, 4/6) FAIL Performance dashboard
apply_patch_parts_dependent_defaults #0 FAIL dashboard
iceberg_suite_s3_read #21 unstable query history
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR corrects missing DEFAULT columns after lightweight updates, including partial patches and pending mutations. One regression in the latest optimization remains: skipping reevaluation bookkeeping also discards shared initial default values, producing projection-dependent results and persisting inconsistent values during merges.

Findings

❌ Blockers

  • MergeTreeReadersChain.cpp:1290: Initial default values must remain shared even when no reevaluation is needed. With missing b UInt64 DEFAULT rand64(), sorting-key column k DEFAULT b, and z DEFAULT b, an unrelated patch to a makes mayReevaluateDefaultsAfterPatches return false. MergeOnKey fills k from one evaluation of b; the subsequent default pass regenerates b for the other columns. On the current CI binary, SELECT z = k returns 1, while additionally selecting patched a returns 0. After OPTIMIZE FINAL, both z = k and b = k remain 0 with apply_patch_parts = 0. The previous PR head, 1b820eb47d69, returns 1 throughout. Preserve intermediates required across initial default passes independently of the reevaluation gate.
Tests
  • ⚠️ All 20 added SQL regression tests pass with the current PR's Fast test binary, but none covers shared initial defaults when the new gate returns false. Add the reproducer above with patch_parts_version = 'v2', comparing projections and checking the materialized result after OPTIMIZE FINAL.
Missing context / blind spots
  • ⚠️ The latest CI workflow limited execution because of an unresolved review thread at configuration time. Full-suite results for this head still require a workflow run after that gate clears.
Final Verdict

Status: ❌ Block

Keep shared initial defaults consistent when the reevaluation gate is false, and add focused regression coverage for reads and merges.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 7, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). label Sep 7, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Confirmed and reproduced, and it needs apply_mutations_on_fly = 1 (the default is 0):

CREATE TABLE t (x UInt32) ENGINE = MergeTree ORDER BY x
SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1;
INSERT INTO t SELECT number FROM numbers(6);
ALTER TABLE t ADD COLUMN a UInt32 DEFAULT 0, ADD COLUMN w UInt32 DEFAULT 7;
ALTER TABLE t ADD COLUMN z UInt32 DEFAULT a + 1000;
SYSTEM STOP MERGES t;
ALTER TABLE t UPDATE w = 8 WHERE 1 SETTINGS alter_sync = 0;   -- stays pending
UPDATE t SET a = 5 WHERE 1;                                   -- a later patch

SELECT a, z, w FROM t;                                    -- 5, 1005, 7  (the mutation is not applied)
SELECT a, z, w FROM t SETTINGS apply_mutations_on_fly = 1; -- 5, 1000, 8  (z is stale)

So the patch for a is applied by the final applyPatchesAfterReader, after the pass that produced z in the last reader step, and z keeps the value the default gave.

I would rather not fold the fix into this pull request. Closing that chain means re-evaluating the dependents after applyPatchesAfterReader, and the "which columns did the defaults produce" set is per reader step and positional (positions_filled_by_defaults indexes the step's own read_columns), while applyPatchesAfterReader works on the accumulated result.columns - so it needs the set carried by name into ReadResult and a way to run evaluateMissingDefaults against the accumulated block. That is a change of its own shape and deserves its own test, and it is not a regression from this one: before this change the single-step case was stale as well, and this narrows the bug rather than moving it.

Filtering columns_patched_after_defaults by the step's version window, the other suggestion, does not change any answer here: a column that this step did not patch keeps its default, so its dependents are re-evaluated from the same value they already had. I left it as is, with the version-window reasoning spelled out in the comment.

I will send the follow-up as a separate pull request unless you would rather have it here.

alexey-milovidov and others added 2 commits September 16, 2026 15:17
…at a step boundary

A lightweight `UPDATE` issued after a mutation that is still pending is applied
only at the boundary of the reader step that applies the mutation on the fly
(`applyPatchesAfterReader`), after that step has already evaluated its missing
`DEFAULT` columns. A `DEFAULT` that reads the patched column therefore kept the
value the default gave: for `a DEFAULT 0, z DEFAULT a + 1000, w DEFAULT 7`, a
pending `ALTER TABLE ... UPDATE w = 8` and a later `UPDATE t SET a = 5`,
`SELECT a, z, w SETTINGS apply_mutations_on_fly = 1` returned `5, 1000, 8`.

`ReadResult` now carries the names of the columns whose value is, so far, the
one their `DEFAULT` expression gave (`columns_filled_by_defaults`). A column
leaves the set when a patch is applied to it (`applyPatches` reports the
columns it did patch, within the step's version window, which also answers the
review remark about `columns_patched_after_defaults`) or when a step's action
recomputes it (an on-fly `UPDATE z = ...` must keep the value it assigned, as
it does once the mutation has materialized the column). After every
`applyPatchesAfterReader` pass that patched something, the remaining columns
of the set are evaluated again from the accumulated block
(`IMergeTreeReader::evaluateDefaults`).

An on-fly mutation step projects the columns the query did not ask for out of
the result into `additional_columns`; the patches are applied to them there as
well, and the last step keeps them, so that `SELECT z, w` sees the patched `a`
through them.

Test `05233_lwu_default_pending_mutation_later_patch` covers both shapes and
the overwriting mutation, and compares the on-the-fly result against the one
read after the mutation has materialized.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… has patches

Without patch parts nothing is ever applied at a step boundary, so there is no
pass to evaluate the columns again and the set would only be filled and dropped.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The follow-up I mentioned above (dependents of a column patched at a step boundary, i.e. a lightweight UPDATE later than a pending mutation applied with apply_mutations_on_fly = 1) is folded into this PR after all, since the AI review marked it as the blocker: see 1c8ab7d, the thread reply, and test 05233_lwu_default_pending_mutation_later_patch. Master merged (5251 commits behind); the only red before this push was the Build profile diff job, tracked in #120121.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov This PR reworks the functions where the abort below happens, so I would rather ask than open something that collides with it.

Both tests here use a pending ALTER TABLE ... UPDATE (a data mutation) with a DEFAULT column outside the sorting key. This shape instead needs a pending MODIFY COLUMN type change whose column is read by a sorting key column's DEFAULT. On master 6bf465b351a2e (26.9.1.1, debug) it aborts. Every setting is a default except the two _block_* columns that lightweight updates require, and the sync settings, which only make the pending window deterministic:

CREATE TABLE r2d (a UInt64, v String, w String) ENGINE = MergeTree ORDER BY a
SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1;
INSERT INTO r2d SELECT number, 'foo', 'w0' FROM numbers(10);
ALTER TABLE r2d ADD COLUMN b UInt64, MODIFY ORDER BY (a, b);
ALTER TABLE r2d MODIFY COLUMN b UInt64 DEFAULT length(w);
SYSTEM STOP MERGES r2d;
SET mutations_sync = 0, alter_sync = 0;
UPDATE r2d SET v = 'bar' WHERE a >= 5;             -- v2 (MergeOnKey) patch part
ALTER TABLE r2d MODIFY COLUMN w FixedString(4);    -- left pending
SELECT a, v, w, b FROM r2d ORDER BY a;
Logical error: 'Unexpected return type from materialize. Expected FixedString(4). Got String.
input block structure:w FixedString(4) String(size = 10)'

read calls readPatches before executeActionsBeforePrewhere, and only the latter calls performRequiredConversions. So when executeSortingKeyExpressions materializes the sorting key column missing on disk, IMergeTreeReader::evaluateMissingDefaults describes the already-read columns by their current metadata type while the data is still the on-disk one, and the materialize output over that inconsistent block trips columnMatchesType. The materializing MUTATE_PART aborts on the same path, so the ALTER does not complete either. apply_mutations_on_fly = 0 is identical; patch_parts_version = 'v1' (Join mode) is correct.

Describing that block truthfully removes the abort, but it also fixes which schema epoch a v2 patch part's stored sorting key is computed in, and the two epochs give different key values for the same row.

Why I read that as a policy choice rather than a local fix

A patch written before the pending ALTER gets perform_alter_conversions = false (AlterConversions.cpp:265, "correctness of ALTER MODIFY may depend on the data in patch part") and stores b = length('w0') = 2; one written after it stores b = length(FixedString(4)) = 4. The patch part does persist that key, and a single read can contain patches of both epochs, so one pre-conversion key silently drops post-ALTER patches, while one post-conversion key silently drops the pre-ALTER patches that :265 exists to keep applicable.

ColumnForPatch::Order is not a proxy for the epoch: getColumnsForPatches tests !column.column first, so any patch whose target column is missing on disk is routed to AfterEvaluatingDefaults regardless of epoch. The epoch is also needed at range selection time, not only at application time, since MergeTreePatchReaderMergeOnKey::needNewPatch / needOldPatch compare the main block's key columns to decide which patch blocks to load, and readPatches hands one main block to every patch reader.

Separately, the same fixture drops a patch with no type change at all: with b UInt64 DEFAULT length(w) and a pending ALTER TABLE ... UPDATE w = 'wxyz' WHERE 1, the on-the-fly read gives v = 'bar' for a >= 5, and once the mutation materializes it gives v = 'foo' for every row.

Which of these do you want?

  1. Persist the key epoch in the patch part and select the reader side key block by it.
  2. Make the producer canonical, always materializing the patch key in one epoch, and define how parts already on disk are read.
  3. Fall back to PatchMode::Join when a sorting key column is DEFAULT or MATERIALIZED derived. Measured correct on master for this fixture today, needs no format change, and also covers the patch drop above.
  4. It is in scope of this PR and I should leave it alone.

I have the repro, the probe matrix (both patch orderings, mixed reads, the mutation path, the v1 control) and a plan for routes 1 to 3; my preference is 3. Related: #119540, whose documented residual points here.

alexey-milovidov and others added 3 commits September 24, 2026 07:08
…hen needed

After the last reader step, `executePrewhereActionsAndFilterColumns` stored every
column the step projected out in `additional_columns` for all queries, which
`ReadResult::applyFilter` then filtered again. They are needed there only by
`MergeTreeReadersChain::applyPatchesAfterReader` to evaluate a `DEFAULT` column
once more, i.e. when there are patch parts and some column of the result still
holds its `DEFAULT` value. Keep them only in that case, restoring the previous
behavior for all other queries.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The "overwriting mutation materialized" step issued `UPDATE z = z WHERE 0` to wait
for the pending `UPDATE z = 3`. `StorageMergeTree` may squash both into one
mutation whose version is above the lightweight `UPDATE`, so the patched `a` was
applied before `z` was materialized (`1007`/`1009` instead of `1000`). Drop that
step; the on-the-fly check above it is the regression test.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118630&sha=431703659e536c627f6140a3683ad2ab23e19377&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29
#118630

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai This is not in scope of this PR (so not option 4), and fixing it separately will not collide with it. This PR only re-evaluates DEFAULT columns after patches are applied (reevaluateDefaultsAfterPatches, evaluateDefaults). It does not change the order of readPatches vs. performRequiredConversions, the sorting-key materialization in executeSortingKeyExpressions, or how MergeOnKey patch readers pick ranges. The exception reproduces on master without this PR, so please open an issue with the repro and your probe matrix. Choosing between routes 1–3 (patch key epoch persisted, canonical producer, or Join fallback for derived sorting key columns) is a design decision; it needs a human maintainer's call, so I am not picking one here.

@groeneai

Copy link
Copy Markdown
Collaborator

Filed as #121943 with the repro, the probe matrix and the three routes, and asked the patch parts owner there for the epoch call. Thanks for the scope ruling; I will keep it out of this PR.

alexey-milovidov and others added 2 commits October 3, 2026 16:05
…tched column

After a patch part overwrote a column, every `DEFAULT` column the step had
filled was evaluated again, including ones unrelated to the patched column.
That evaluated a non-deterministic `DEFAULT` such as `rand()` twice and
did needless work. Add `IMergeTreeReader::getDefaultsDependingOn`, which
returns the candidates whose `DEFAULT` expression reads a changed column,
directly or through another `DEFAULT` column the part does not store, and
use it in both re-evaluation passes.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master and pushed 5f2b9d2, which addresses the last open AI review thread (only DEFAULT columns that read a patched column are evaluated again). The only red on the previous head was Upgrade check (amd_release): the previous release fails to attach t_pfl_05079 (AggregateFunction(quantile('0.5'), Float64), Cannot convert String to double), which is unrelated to this PR.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118630&sha=0ebcb3fdc7d6e72f7e16c93a32c4bf7ecbe675aa&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator

Same failure as on #119307, and it is already fixed, so there is no new PR from me.

The run on 0ebcb3fd (2026-09-24) upgraded from v26.9.2.8-stable (job.log line 259), which predates the fix. #121590 (@ azat, merged into 26.9 on 2026-09-22) stops 05079 from creating t_pfl_05079, and v26.9.3.38-stable (2026-09-26) is the first release with it. The last t_pfl_05079 hit in CIDB is 2026-09-26 13:10 UTC, with 0 in the 2,046 upgrade-check runs since. Current runs upgrade from v26.9.8.3-stable and pass. Upgrade check (amd_release) has not started yet on 5f2b9d28b42.

…shared intermediate

`evaluateDefaultsInRowsFilledByDefaults` added every requested candidate reading a missing
intermediate evaluated again, bypassing the sort-key exclusion of `getDefaultsDependingOn`.
With `k DEFAULT b`, `b DEFAULT a + 100` and `z DEFAULT a + b`, a lightweight `UPDATE` of `a`
changed `k` when `z` was requested, breaking the order of ordered reads.

Add `IMergeTreeReader::isSortingKeyColumn` and skip sort-key columns in that expansion.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 5 commits November 8, 2026 23:36
…ULT` reads

A sort-key column the part does not store keeps the value its `DEFAULT` gave
before patches. When it was not requested, a `DEFAULT` column reading it was
evaluated again after a lightweight `UPDATE` through an intermediate computed
anew from the patched input, so `SELECT z` gave a value different from
`SELECT a, k, z`. Inject such a column into the read columns when the part has
patches, so it is filled once, before the patches, as if it was requested.

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

When the sorting key reads a subcolumn (`ORDER BY (id, k.x)`), the list of
columns required for the sorting key holds `k.x`, while the injection of a
missing sort-key column read by a `DEFAULT` compared it with the storage name
`k`, so `k` was not retained and a re-evaluated `z DEFAULT a + k.1` depended on
whether `k` was selected. Both the injection and the re-evaluation exclusion now
use one set of sort-key storage names from `getSortingKeyColumnsInStorage`.

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

`k UInt64 DEFAULT b` in the sorting key keeps the value its `DEFAULT` gave, while
`z DEFAULT a + b` is evaluated again after a patch to `a`. With `b DEFAULT rand64()`
not stored and not requested, the evaluation after the patch synthesized a new `b`,
so `z = k + a` no longer held in a row.

`ReadResult::default_intermediates` now keeps the missing columns evaluated from their
`DEFAULT` while patch parts are read. A later evaluation, the one after patches or the
one of a later step (including the sort-key columns evaluated before the patches of
format `v2`), reads these values instead of synthesizing new ones. A column leaves the
set when a column its `DEFAULT` reads is patched or recomputed by a step, as its value
is then stale and it is evaluated anew.

New test `05617_lwu_default_sorting_key_consumer_of_intermediate` covers patch formats
`v1` and `v2` and the pending-mutation step boundary.

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

Copy link
Copy Markdown
Member Author

🕵 Merged the latest master into the branch and pushed it as 5079c89beb12. There were no conflicts and the PR diff is unchanged. All six changed translation units (IMergeTreeReader.cpp, MergeTreeBlockReadUtils.cpp, MergeTreeRangeReader.cpp, MergeTreeReadersChain.cpp, applyPatches.cpp, applyPatchesLegacy.cpp) compile on the merged tree.

State on b124e8f05baa:

  • The AI review approves, and every review thread is resolved.
  • The only red check is Performance Comparison (arm_release, master_head, 3/6), for apply_patch_parts_dependent_defaults #0 (0.40 s -> 0.93 s). This PR adds that test. On master the query skips the patch and returns stale values; with this PR it reads the patch and evaluates the dependent DEFAULT columns again. That extra work is the cost of the fix, so this check will stay red on this PR until a maintainer accepts it.
  • The CHANGES_REQUESTED review from 2026-09-23 is stale: both of its points were fixed in 0ebcb3f and 1620d6a. A maintainer needs to re-review or dismiss it.

alexey-milovidov and others added 2 commits November 14, 2026 11:07
…ion step as read

An on-fly mutation step projects its inputs: after it, the block holds only
the outputs of its actions. `getReadTaskColumns` still recorded every column
read in earlier steps as available, so a subcolumn `b.x` injected to evaluate
`z DEFAULT b.x + 1` (because a patch part updates `b`) was not read again by
the last step, while the mutation step kept only its parent `b`. A query
selecting `b.x` then threw `NOT_FOUND_COLUMN_IN_BLOCK`.

Mark `PrewhereExprStep::project_inputs` for such steps and, after one, keep
as available exactly the outputs of its actions.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118630&sha=5079c89beb126a043700a021209509d83c3cf0f7&name_0=PR&name_1=La%20Casa%20Del%20Dolor%20%28amd_tsan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. It is a ThreadSanitizer data race reported in the BuzzHouse client process (fuzzer.log, the client stack has no MergeTree reading), not in the server, so it does not look related to this PR.

@groeneai

Copy link
Copy Markdown
Collaborator

This is the client-side race fixed by #131177 (merged 2026-11-13 09:14 UTC), so no new PR is needed.

Symbolized with this run's binary (BuildId 3781f4aa): the main thread applies the server's TimezoneUpdate (ClientBase::onTimezoneUpdate -> setSetting("session_timezone"), called from receiveLogsAndProfileEvents in sendDataFrom) while the QueryPullPipeEx thread parsing the VALUES of an INSERT ... RETURNING reads session_timezone in DateLUT::instance. #131177 applies the TimezoneUpdate before the parsing pipeline starts.

This run's tree predates the fix; the current head 244701522478 contains it. Since the merge, La Casa Del Dolor (amd_tsan) has 295 successful runs and no Client failure on a tree with the fix.

alexey-milovidov and others added 2 commits November 16, 2026 09:34
…mutation step

A subcolumn `b.x` read to evaluate `z DEFAULT b.x + 1` is patched in the
first step and then projected out by an on-fly mutation step that keeps
only its parent `b`. The last step reads `b.x` from the disk again, but
`ReadResult::patch_versions_block` still held the versions of the earlier,
already patched instance, so the patch skipped its rows and the query
returned the old value of `b.x` next to the patched `b`.

Forget the recorded versions of the columns read in a step: they are new
instances of the data, just read from the disk.

Add a case with `b` stored in the part to
`05768_lwu_default_injected_subcolumn_mutation_on_fly`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 19, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 State on 1b820eb47d69: the AI review approves, every review thread is resolved, and there are no conflicts with master. The only red check is Performance Comparison (arm_release, master_head, 2/6) for apply_patch_parts_dependent_defaults #0 (0.36 s -> 0.90 s). This PR adds that test. On master the query ignores the patch for the dependent DEFAULT columns and returns stale values. This PR evaluates those columns again from the patched values, and that extra work is the cost of the fix. No change on the branch can turn this check green, so a maintainer has to accept the regression. The CHANGES_REQUESTED review from 2026-09-23 is out of date: 0ebcb3f and 1620d6a addressed both of its points. It needs a re-review or a dismissal. I did not merge master again in this pass, because the branch was updated today and the merge would not change this check.

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

Two comments here:

  1. the change looks extremely long and complicated. Are we sure that we are not overenginering here?

  2. I see some red in the CI for perf test. DO we really need to accept that?

alexey-milovidov and others added 2 commits November 22, 2026 20:39
… may change their inputs

The state kept to evaluate a `DEFAULT` column again after patch parts are applied
(`columns_filled_by_defaults`, `rows_filled_by_defaults`, `default_intermediates` and the
columns projected out by the last step) was kept whenever the part had patches, even if no
`DEFAULT` expression reads a patched column. `ReadResult::applyFilter` and `shrink` then
filtered the missing `DEFAULT` columns a second time in every `PREWHERE` step.

`MergeTreeReadersChain::mayReevaluateDefaultsAfterPatches` now checks, once per chain and only
when the part lacks a `DEFAULT` column, whether a patch part may overwrite a column that the
`DEFAULT` expression of a missing column reads. If not, `getDefaultsDependingOn` can return
nothing, so none of that state is kept and the patches are applied as before this change.

Also skip the loop erasing stale patch versions when `patch_versions_block` is empty: it built
a version column name for every column of every step and block, including in queries without
patches.

Add the performance test `apply_patch_parts_unrelated_defaults` for a `PREWHERE` query reading
many missing `DEFAULT` columns that do not read the patched column.

Related: #118630

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @Ergus, on the two points of your review of 2026-11-20 (both inline threads are answered and fixed in 7a583f3, which also merges the latest master):

  1. Size of the change. The core fix is small: evaluate the missing DEFAULT columns once more after a patch overwrote a column they read. Most of the code handles cases the AI review and the tests found on the way, each with its own test: rows a patch overwrote must keep the patched value (the evaluation is per row), a non-deterministic DEFAULT such as rand() must not change when an unrelated column is patched, sort-key columns must keep their value, subcolumns and Nested fields, patches applied at a step boundary after an on-fly mutation. I do not see one of these that can be dropped without returning a wrong result in that case. With the new gate, none of this code runs unless a patch can change the input of a missing DEFAULT.

  2. The red perf check. It is apply_patch_parts_dependent_defaults #0 (0.36 s -> 0.90 s), a test this PR adds. The baseline is master, where this query returns stale values for the 64 dependent columns, i.e. it does less work and the result is wrong. The PR evaluates those columns a second time from the patched values. So the comparison is not between two correct implementations, and I do not know a change on the branch that makes this check green while keeping the test. Options: accept the red for this one query, or drop this perf test from the PR and add it in a follow-up once the fix is in master (then it has a meaningful baseline). I kept the test for now; tell me if you prefer the second option. The queries that existed before are not affected, and the new apply_patch_parts_unrelated_defaults test covers the path that must stay as fast as on master.

clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 22, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @Ergus, I resolved the thread about the bookkeeping cost for unrelated DEFAULT columns: 7a583f3 skips all of that state unless a patch part may overwrite a column that a missing DEFAULT reads, and apply_patch_parts_unrelated_defaults.xml covers your example. While the thread was open, the review-threads gate limited CI to builds and preliminary checks, so the fix had not been through the full suite; it will run now. The limit I described in the reply (the check is per chain, not per column) still stands, so please reopen the thread if you want that narrowed in this PR. Your CHANGES_REQUESTED review still needs your re-review.

addDummyColumnWithRowCount(additional_columns, result.num_rows);
range_reader.getReader()->evaluateMissingDefaults(additional_columns, columns);
range_reader.getReader()->evaluateMissingDefaults(
additional_columns, columns, mayReevaluateDefaultsAfterPatches() ? &result.default_intermediates : nullptr);

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] Preserve first-pass default intermediates when reevaluation is unnecessary

A false result from mayReevaluateDefaultsAfterPatches now also disables retaining the initial default values. Those values are needed even when no default reads a patched column: executeSortingKeyExpressions evaluates missing defaults to obtain the key, retains only the key, and the ordinary default pass subsequently evaluates the other columns. With this gate disabled, the two passes generate different values for the same missing intermediate.

Reproduced with the 7a583f3089f8 Fast test binary:

SET allow_experimental_lightweight_update = 1;
CREATE TABLE t (id UInt32) ENGINE = MergeTree ORDER BY id
SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1,
         apply_patches_on_merge = 0, patch_parts_version = 'v2';
INSERT INTO t VALUES (0), (1);
SYSTEM STOP MERGES t;
ALTER TABLE t ADD COLUMN a UInt64 DEFAULT 5;
ALTER TABLE t ADD COLUMN b UInt64 DEFAULT rand64();
ALTER TABLE t ADD COLUMN k UInt64, MODIFY ORDER BY (id, k);
ALTER TABLE t MODIFY COLUMN k UInt64 DEFAULT b;
ALTER TABLE t ADD COLUMN z UInt64 DEFAULT b;
UPDATE t SET a = 5 WHERE 1;
SELECT id, z = k FROM t ORDER BY id;
SELECT id, a, z = k FROM t ORDER BY id;
ALTER TABLE t MODIFY SETTING apply_patches_on_merge = 1;
SYSTEM START MERGES t;
OPTIMIZE TABLE t FINAL;
SELECT id, z = k, b = k FROM t ORDER BY id SETTINGS apply_patch_parts = 0;

The first query returns equality 1 for both rows; adding the unrelated patched a makes it 0. The final query returns both equalities as 0, so the merge persists the inconsistency. The previous PR head, 1b820eb47d69, returns 1 throughout, as does the current binary before the update.

Please separate retention needed across initial default passes from the reevaluation bookkeeping, retaining shared inputs when a key is filled early even if the predicate is false. Add this gate-disabled case to the regression coverage, including the merged result.

@clickhouse-gh
clickhouse-gh Bot dismissed stale reviews from themself November 23, 2026 05:36

AI review of a later commit does not approve the PR, see the AI Review comment.

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-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Lightweight UPDATE of a base column returns a stale DEFAULT-column value when both columns are absent from the part (disagrees with heavy ALTER UPDATE)

3 participants