Skip to content

Fix column not found error for lazy materialization and part_offset i… - #108287

Merged
vdimir merged 3 commits into
masterfrom
vdimir/lazy_materialization_part_offset_prewhere
Jul 23, 2026
Merged

vdimir merged 3 commits into
masterfrom
vdimir/lazy_materialization_part_offset_prewhere

Conversation

@vdimir

@vdimir vdimir commented Jun 23, 2026 •

Copy link
Copy Markdown
Member

…n prewhere

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 NOT_FOUND_COLUMN_IN_BLOCK error for queries that use the _part_starting_offset/_part_offset virtual columns in WHERE together with lazy materialization

Close #108126

Version info

  • Merged into: 26.7.1.1382 (included in 26.7 and later)
  • Backported to: 26.7.2.10, 26.6.2.106, 26.5.6.68, 26.4.5.155, 26.3.17.72

@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cb4a75f]

Summary: ✅


AI Review

Summary

This PR fixes the lazy-materialization path when _part_starting_offset / _part_offset are consumed by PREWHERE or row-policy filters: ReadFromMergeTree::addStartingPartOffsetAndPartOffset now re-exposes those inputs in the filter DAG, or disables filter-column removal when the virtual column itself is the filter output. I re-checked the earlier inline issue against the current head, read the touched source and test paths, and did not find any remaining correctness problem in the changed code.

Final Verdict

✅ No blocking issues found in the current PR head.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 23, 2026
if (!filter_actions)
continue;
auto & dag_outputs = filter_actions->getOutputs();
for (const auto * input : filter_actions->getInputs())

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.

I think if the row policy has it as input but the prewhere not, than we will fail to expose this in the output. We have to add it to the prewhere actions if it is not present.

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.

Okay, after thinking more about it: this probably cannot happen, because we don't push thing into row policies. However I think this is inconcistent: we should either don't touch row level filter or handle the case when row level filter doesn't output it.

@vdimir vdimir Jun 23, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

If the row policy has _part_starting_offset as an input but PREWHERE does not, then that column will be bypassed.
The other way around also works as expected: if the row policy does not have _part_starting_offset, but PREWHERE does.
This is I assume how expression calculation works: if we merge DAGs where the second one has an unknown output from the previous one, it passes it further, and which is intentional.

That said, the only important thing is to add the column to the output if it is present in the inputs. Otherwise, in this case, it will be dropped.

Please check my example. I will add this to the test cases, but overall I think the current version of the code covers this. Let me know what you think.

Details
DROP ROW POLICY IF EXISTS repro_pol2 ON repro;
DROP ROW POLICY IF EXISTS repro_pol ON repro;
DROP TABLE IF EXISTS repro;

CREATE TABLE repro (Id UInt64, EventId UInt64, flag UInt8) ENGINE = MergeTree ORDER BY Id;
INSERT INTO repro SELECT number, number, number % 2 FROM numbers(1000);

SET query_plan_optimize_lazy_materialization = 1;

CREATE ROW POLICY repro_pol ON repro USING _part_starting_offset + _part_offset < 100 TO ALL;

SELECT repeat('-----', 10);

EXPLAIN PLAN actions = 1
SELECT EventId FROM repro WHERE Id < 10 ORDER BY Id DESC LIMIT 10;

SELECT repeat('-----', 10);

EXPLAIN PLAN actions = 1
SELECT EventId FROM repro WHERE Id < 10 AND _part_starting_offset + _part_offset < 50 ORDER BY Id DESC LIMIT 10;

DROP ROW POLICY repro_pol ON repro;
CREATE ROW POLICY repro_pol2 ON repro USING Id < 10 TO ALL;

SELECT repeat('-----', 10);
EXPLAIN PLAN actions = 1
SELECT EventId FROM repro WHERE _part_starting_offset + _part_offset < 50 ORDER BY Id DESC LIMIT 10;

EXPLAIN results:

https://pastila.nl/?0028a77c/7af9cd4ece2e6a9aeeefb2013723a009#hC7F5r4fVo0SSNJvqY9Drg==GCM

...
Prewhere filter
Prewhere filter column: less(__table1.Id, 10_UInt8) (removed)
Actions: INPUT : 0 -> Id UInt64 : 0
            COLUMN Const(UInt8) -> 10_UInt8 UInt8 : 1
            FUNCTION less(Id : 0, 10_UInt8 :: 1) -> less(__table1.Id, 10_UInt8) UInt8 : 2
Positions: 0 2
Row level filter
Row level filter column: less(plus(_part_starting_offset, _part_offset), 100_UInt8) (removed)
Actions: INPUT : 0 -> _part_starting_offset UInt64 : 0
            INPUT : 1 -> _part_offset UInt64 : 1
            COLUMN Const(UInt8) -> 100_UInt8 UInt8 : 2
            FUNCTION plus(_part_starting_offset : 0, _part_offset : 1) -> plus(_part_starting_offset, _part_offset) UInt64 : 3
            FUNCTION less(plus(_part_starting_offset, _part_offset) :: 3, 100_UInt8 :: 2) -> less(plus(_part_starting_offset, _part_offset), 100_UInt8) UInt8 : 4
Positions: 4 0 1
...

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.

If the row policy has _part_starting_offset as an input but PREWHERE does not, then that column will be bypassed.
The other way around also works as expected: if the row policy does not have _part_starting_offset, but PREWHERE does.

Yes, you are right. I forgot about bypassed columns.

@vdimir

vdimir commented Jun 26, 2026

Copy link
Copy Markdown
Member Author

@groeneai please check CI failures have inflight fixes

@groeneai

Copy link
Copy Markdown
Collaborator

@vdimir checked all failing checks on 2b3ba0e. None are caused by this PR (your diff is the ReadFromMergeTree.cpp read path; every failure below is an unrelated write/merge path or a known trunk flake). Each has an in-flight fix except the segfault, which is an open trunk bug already tracked.

Check Failure In-flight fix / status
Integration (db disk, old analyzer, 4/6) test_s3_plain_rewritable: Code: 36 ... REPLACE PARTITION ... has no parts in partition 1: refusing because it would silently drop the destination partition's data Fixed on master: #108350 (merged 06-25) opts the test into allow_replace_partition_from_empty_source = 1. Your branch predates it. Behavior change = #104939 (data-loss fix for #23727). Rebase / merge master to pick it up.
Stateless (arm_asan_ubsan, azure, sequential) Segfault STID 0883-4c00 (Server died; 03381_query_result_cache_in_where_subqueries is a victim). Free-time SIGSEGV in ASan Allocator::Deallocate: cross-thread double-free, MergeTree part-removal cleanup metadata ReadBuffer vs horizontal-merge output column buffer No fixing PR yet (the OOB writer is not captured in any stack, not locally reproducible). Open trunk heap-corruption family, recurs across ~8 unrelated PRs incl. master over 30d. Tracked in #106370.
Stress (arm_tsan) "Hung check": runaway server-side AST-fuzzer INSERT (t_null_carrying_wide, elapsed 960s); server stayed responsive (answered SELECT 1). Not a deadlock In-flight: #108212 (limit + cancel in-flight AST-fuzzer queries). Complementary in-flight per-granule cancel: #108357, #108351, #108353.
Stress (arm_ubsan) "Hung check": runaway fuzzed INSERT from 04357_set_skip_index_lowcardinality_hastoken_like, 1123s in skip-index calculation (elapsed 1236s). Not a deadlock Same owner as arm_tsan: #108212 (+ #108357/#108351/#108353). Chronic stress class: ~471 distinct PRs + 348 master hits over 30d, all sanitizer variants.
CH Inc sync private mirror not actionable, not a merge gate

@vdimir

vdimir commented Jul 16, 2026

Copy link
Copy Markdown
Member Author
  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:3561-3590] addStartingPartOffsetAndPartOffset still loses the virtual column when the filter column is exactly _part_offset or _part_starting_offset (for example SELECT EventId FROM repro WHERE _part_offset ORDER BY Id DESC LIMIT 10, or a row policy USING _part_offset). In that shape the input node is already present in dag_outputs as the filter output, so reexposed never becomes true. The fallback all_column_names.insert does not save it: ActionsDAG::updateHeader removes matched inputs from the pass-through set, and remove_prewhere_column / do_remove_column then erases the only remaining virtual column again. Both src/Processors/QueryPlan/Optimizations/optimizeLazyMaterialization.cpp:361-381 and src/Processors/Sources/LazyReadReplacingFinalSource.cpp:88-106 rely on this helper before building __global_row_index, so the direct-column predicate still ends with a NOT_FOUND_COLUMN_IN_BLOCK exception instead of the fixed behavior promised by the PR.
    Suggested fix: when the preserved column is already the filter output, treat that as re-exposed and clear remove_prewhere_column / do_remove_column for that exact filter, or add a separate pass-through output / alias that survives filter-column removal. Add a regression for WHERE _part_offset (and ideally the row-policy variant), because the current test only covers derived predicates like _part_starting_offset + _part_offset < 100.

@groeneai try to reproduce this issue on this branch or determine whether this comment is valid.

@groeneai

Copy link
Copy Markdown
Collaborator

@vdimir Confirmed valid, reproduced on this branch head (b985d63, debug). Two shapes throw NOT_FOUND_COLUMN_IN_BLOCK when the filter column is exactly _part_offset:

CREATE TABLE repro (Id UInt64, EventId UInt64, flag UInt8) ENGINE = MergeTree ORDER BY Id;
INSERT INTO repro SELECT number, number, number % 2 FROM numbers(1000);

-- (1) explicit PREWHERE on the bare virtual column
SELECT EventId FROM repro PREWHERE _part_offset ORDER BY Id DESC LIMIT 10
  SETTINGS query_plan_optimize_lazy_materialization=1, query_plan_max_limit_for_lazy_materialization=100;
-- Code: 10. Not found column _part_offset: in block _part_starting_offset ..., Id ...

-- (2) row policy USING the bare virtual column
CREATE ROW POLICY p ON repro USING _part_offset TO ALL;
SELECT EventId FROM repro ORDER BY Id DESC LIMIT 10
  SETTINGS query_plan_optimize_lazy_materialization=1, query_plan_max_limit_for_lazy_materialization=100;
-- same Code: 10

Server stack: ActionsDAG::updateHeader (ActionsDAG.cpp:1402) inside optimizeLazyMaterialization2 (optimizeLazyMaterialization.cpp:620). In expose_in_output, the guard input->result_name == column_name && find(dag_outputs, input) == dag_outputs.end() is false because the bare virtual column is already the filter output, so reexposed never flips; the all_column_names.insert fallback is then dropped by updateHeader / remove_prewhere_column, exactly as the comment describes.

One correction to the review's literal example: WHERE _part_offset (implicit move-to-prewhere) actually passes here. It is the explicit PREWHERE _part_offset and the row-policy USING _part_offset shapes that fail. Derived predicates such as _part_starting_offset + _part_offset < 100 (what the current test covers) are fine.

If you want, I can send a suggestion that treats the filter-output-preserved column as re-exposed (clear remove_prewhere_column/do_remove_column for that exact filter) plus a regression for both shapes above.

@vdimir
vdimir force-pushed the vdimir/lazy_materialization_part_offset_prewhere branch from b985d63 to cb4a75f Compare July 22, 2026 16:48
@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.10% 86.20% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.20% 78.30% +0.10%

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

Full report · Diff report

@vdimir

vdimir commented Jul 23, 2026

Copy link
Copy Markdown
Member Author

Stress test (amd_debug) FAIL
Logical error: Got read request from replica A for unknown stream B. (STID: 5217-505b) FAIL cidb

@groeneai is it known failure?

@vdimir
vdimir added this pull request to the merge queue Jul 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

Got read request from replica A for unknown stream B. (STID: 5217-505b) is it known failure?

Yes, and it is unrelated to this PR.

5217-505b is the chronic parallel-replicas coordinator LOGICAL_ERROR (ParallelReplicasReadingCoordinator::handleRequest). Fresh CIDB over the last 30 days: 65 distinct PRs plus 3 master runs, spread across Stress (all sanitizers), the coverage ParallelReplicas job, and the AST fuzzer, so it is trunk-wide, not build-specific. The diff here does not touch the coordinator or the RemoteQueryExecutor read path, so the Stress amd_debug hit is not caused by this change.

Tracked in #110518 (comp-parallel-replicas; sibling STID 5217-5b3d, same message). A prior fix attempt (#109202) was closed unmerged and there is no open fix PR at the moment.

Merged via the queue into master with commit e30f537 Jul 23, 2026
354 of 355 checks passed
@vdimir
vdimir deleted the vdimir/lazy_materialization_part_offset_prewhere branch July 23, 2026 12:03
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 23, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 23, 2026
robot-ch-test-poll added a commit that referenced this pull request Jul 23, 2026
Cherry pick #108287 to 25.8: Fix column not found error for lazy materialization and part_offset i…
robot-clickhouse added a commit that referenced this pull request Jul 23, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 23, 2026
clickhouse-gh Bot added a commit that referenced this pull request Jul 23, 2026
Backport #108287 to 26.6: Fix column not found error for lazy materialization and part_offset i…
clickhouse-gh Bot added a commit that referenced this pull request Jul 23, 2026
Backport #108287 to 26.7: Fix column not found error for lazy materialization and part_offset i…
vdimir added a commit that referenced this pull request Jul 23, 2026
Backport #108287 to 26.3: Fix column not found error for lazy materialization and part_offset i…
vdimir added a commit that referenced this pull request Jul 23, 2026
Backport #108287 to 26.4: Fix column not found error for lazy materialization and part_offset i…
vdimir added a commit that referenced this pull request Jul 23, 2026
Backport #108287 to 26.5: Fix column not found error for lazy materialization and part_offset i…
UnamedRus pushed a commit to UnamedRus/ClickHouse that referenced this pull request Aug 12, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…rialization_part_offset_prewhere

Fix column not found error for lazy materialization and part_offset i…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.2-must-backport v26.3-must-backport v26.4-must-backport v26.5-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Column not found error in case of lazy materialization applied for query referencing _part_starting_offset in WHERE

6 participants