Skip to content

Apply a row policy that uses currentUser() or now() before FINAL again - #130536

Merged
fm4v merged 5 commits into
ClickHouse:masterfrom
groeneai:row-policy-before-final-with-query-constant
Nov 13, 2026
Merged

fm4v merged 5 commits into
ClickHouse:masterfrom
groeneai:row-policy-before-final-with-query-constant

Conversation

@groeneai

@groeneai groeneai commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #130317
Related: #117248

Changelog category (leave one):

  • Performance Improvement

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

A FINAL query on a table whose row policy compares ORDER BY columns with a value computed once per query, such as currentUser(), now() or an IN (subquery) set, applies the policy before the merge again, as in 26.8, instead of reading and merging every row first. On GraphiteMergeTree this holds only for a policy on the path column when it leads ORDER BY. Closes #130317.

Description

Since 26.9 a row policy like c2 = substring(currentUser(), 1, 3) on an ORDER BY column is applied after FINAL, and PREWHERE with it, so the whole table is read and merged before the policy filters it. On the query in #130317 this costs 9.7x memory and 2.7x time. Policies using now(), currentDatabase() or IN (subquery) are deferred too.

#117248 added node->isDeterministic() to isNodeDeterministic, the gate of isRowPolicyDeferredAfterFinal. For a COLUMN node it returns is_deterministic_constant, which the analyzer sets to false for a constant folded from a non-deterministic function. A constant has one value for the whole query, so it cannot split a dedup group. Two exceptions stay deferred: a lambda folded into a constant, whose body allNodeFunctions checks (05141, 05182), and the set of a Set table, also when a lambda captures it, which a concurrent INSERT changes while the query runs. This PR replaces that check with one for such sets. I do not propose reverting #117248: it fixes wrong results (#117016).

GraphiteMergeTree rolls up rows with different times, so the check now takes its columns from getSortingKeyNamesSafeBeforeFinal, as PREWHERE does: only a policy on the path column, when it leads ORDER BY, runs before the rollup. A literal time policy, which master applies before the rollup, now runs after it too.

Validation: new test 05616_row_policy_after_final_query_constant fails on master (the policy is deferred) and passes 50/50 with random settings, in the parallel-replicas flavour and with serialize_query_plan = 1. New performance test final_row_policy_query_constant. On the master release build with the issue's data, the currentUser() policy (master's plan) against the same policy as a literal (this PR's plan): 0.093 s / 1.20 GiB against 0.029 s / 288 MiB, and 0.183 s / 3.47 GiB against 0.033 s / 453 MiB with compatibility = '24.0' (medians of 10).

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2151-master (included in 26.11 and later)

ClickHouse#117248 made `isNodeDeterministic` also reject a `COLUMN` node whose
`is_deterministic_constant` flag is false. The analyzer sets that flag
to false for a constant folded from a non-deterministic function, so a
row policy like `c2 = substring(currentUser(), 1, 3)` over `ORDER BY`
columns started to look non-deterministic. `isRowPolicyDeferredAfterFinal`
then deferred it after `FINAL`, and PREWHERE with it, so the whole table
was read and merged before the policy filtered it (ClickHouse#130317: 9.7x memory,
2.7x time on 26.10 against 26.8). The same happened for `now()`,
`currentDatabase()` and `IN (subquery)` sets.

Before FINAL the policy only has to give every version of one key the
same verdict. A constant has one value for the whole query, so it cannot
split a dedup group, whatever its cross-query determinism. Only a lambda
folded into a constant is evaluated per row, and `allNodeFunctions` plus
the carrier check below it still look into its body, so the ClickHouse#117248
cases (05141, 05182) stay deferred. The flag itself is unchanged: the
query condition cache still needs it.

Closes ClickHouse#130317

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

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

Pre-publication review by an independent model (engine: codex; 2 findings) plus my own review (3 nits).

# Sev Finding Verdict Evidence / action
1 ❌ On GraphiteMergeTree a Time policy with now() now filters before the rollup, which changes the result DISAGREE On master the same policy with a literal time is already applied before the rollup (rollup value 2); only the now() spelling is deferred, and its value 4 includes the two rows the policy hides. 26.8 applied both before the rollup. The WHERE to PREWHERE rule for Graphite (05441) is about query conditions, not row policies. Graphite row-policy semantics are #112817's (it puts policies on blending engines before FINAL); no change here, disclosed in the description
2 💡 The apply_row_policy_after_final doc should say "does not prevent this" rather than "does not make the expression non-deterministic" AGREE, not fixed Wording only; in context the sentence defines what this check counts as deterministic
3 💡 The carrier check after allNodeFunctions in isNodeDeterministic repeats its COLUMN branch AGREE, not fixed Existing code, outside this diff
4 💡 "under parallel replicas" in the description: FINAL is never read with parallel replicas AGREE, fixed Reworded to the parallel-replicas CI flavour

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

Session id: cron:clickhouse-review-slot-8:20261110-145400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. EXPLAIN actions = 1 of SELECT * FROM t FINAL under a currentUser(), now() or IN (subquery) row policy on ORDER BY columns prints a Deferred row level filter line on master, every run. The new test fails on master 5/5.
b Root cause explained? isNodeDeterministic (the gate of isRowPolicyDeferredAfterFinal) calls node->isDeterministic() since #117248. For a COLUMN node that returns is_deterministic_constant, false for a constant folded from currentUser()/now()/an IN set, so the policy is deferred after FINAL and PREWHERE with it.
c Fix matches root cause? Yes. The check is removed from that one gate; allNodeFunctions still checks folded-lambda bodies. The flag, the analyzer and the query condition cache gates are unchanged.
d Test intent preserved / new tests added? New 05616_row_policy_after_final_query_constant (EXPLAIN count + FINAL row counts, with a non-sorting-key control) and perf test final_row_policy_query_constant. The 12 related tests (03742, 03743, 03928, 04340, 04833, 05045, 05059, 05141, 05166, 05182, 05241, 05453) pass unchanged.
e Both directions demonstrated? Master: EXPLAIN counts 1/1/1, test FAILS. Fix: 0/0/0, test passes; row counts identical in both. Issue repro (debug A/B): ReadCompressedBytes 128.2 MB on master, 47.0 MB with the fix, equal to the literal policy.
f Fix is general across code paths? isNodeDeterministic has one caller; isPrewhereDeferredAfterFinal follows it. The WHERE-to-PREWHERE gate under FINAL already accepts plain constants, so both gates now agree.
g Fix generalizes across inputs (params/datatypes/wrappers)? Probed LowCardinality, Nullable and Array constants, currentDatabase(), randConstant(): no longer deferred. rand(), randConstant inside a lambda and non-sorting-key policies stay deferred. Parallel replicas (local plan 0 and 1) and serialize_query_plan = 1: 20/20 each.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default or format change; the 26.8 placement comes back.
i Invariants and contracts preserved? A row-level filter applied before FINAL gives every version of one sorting key the same verdict: a per-query constant cannot differ between rows, and per-row lambdas are still rejected. The countIf(payload = 'old') = 0 rows show no superseded version leaks.

Session id: cron:clickhouse-impl-slot-6:20261110-140200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @yariks5s @antaljanosbenjamin, could you review this and add the can be tested label so CI runs? Since #117248, isNodeDeterministic rejects a constant folded from currentUser(), now() or an IN (subquery) set, so an ORDER BY-only row policy is deferred after FINAL together with PREWHERE; this PR drops that one check (folded lambda bodies are still checked), which restores the 26.8 placement.

@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5c76124]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Query builder not found for text search query with function 'A (STID: 3694-54bc) FAIL cidb IGNORED

AI Review

Summary

This PR restores row-policy filtering before FINAL when sorting-key predicates use query constants, while retaining deferral for mutable Set tables and non-deterministic lambdas. The latest commit addresses the earlier GraphiteMergeTree finding by restricting early filtering to its leading path column. No unresolved findings remain. The new regression test and five related row-policy tests pass in the head commit's Fast test report; the description also provides performance measurements and the diff adds a focused performance test.

Final Verdict

Status: ✅ Approve. No new inline findings.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5c76124f8 with master 1e5f1a9a8 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.82, programs/clickhouse-keeper ×0.68 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.7 s 14.5 s +9.1 s (+167%)
Compile time of recompiled translation units

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

Job report

perf.py runs every query of a performance test through
string.Formatter, so the literal `{"p":` in both fill queries was read
as a placeholder named `"p"` and the test failed with KeyError before
measuring anything. Double the braces: they render back to single
braces, so the SQL the server runs is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@yariks5s yariks5s self-assigned this Nov 10, 2026
groeneai and others added 2 commits November 11, 2026 01:42
…ables

The Iceberg configuration of the performance comparison rewrites the
test's ReplacingMergeTree table to IcebergLocal/IcebergS3, and its only
query fails with `Storage IcebergLocal doesn't support FINAL`, so the
report of all six `iceberg_local|iceberg_s3` shards fails. The test
measures where MergeTree applies a row policy relative to FINAL, which
has no Iceberg counterpart, so opt it out with `<test iceberg="0">`
rather than the skip list (changing the skip list would run the whole
Iceberg configuration in this pull request), as d350f35 does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`StorageSet::insertBlock` inserts into the very `Set` object a running
query holds (`FutureSet::isMutableDuringQuery`), so a policy such as
`k IN set_table` can give two versions of one key different verdicts
when an `INSERT` into the `Set` table lands between the reads of their
parts, and FINAL then returns a superseded version. On master such a
policy stays after FINAL only because ClickHouse#117248 rejected every constant
folded from a non-deterministic expression, and the set of any `IN` is
marked that way; dropping that check would have moved it before FINAL.

Refuse a `ColumnSet` whose set is mutable during the query, also when
a folded lambda captures it (`arrayExists(x -> x IN set_table, [k])`),
where the planner passes the set to the lambda as a captured column.
The set of `IN (subquery)` is built once by the query and frozen, so it
is still applied before FINAL.

Also reword the setting description: such a query-wide value is still
marked non-deterministic, it just no longer prevents the optimization.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 11, 2026

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

@groeneai The blocker is moving row policies before FINAL for GraphiteMergeTree. The new determinism check accepts query constants, but the accompanying sorting-key check assumes that filtering by a sorting key preserves FINAL results. Graphite rollups violate that assumption: they combine different timestamps and round the resulting timestamp. See isNodeDeterministic.

I reproduced this against the exact base and PR binaries, with apply_row_policy_after_final = 1. Two rows have values 1 and 2, timestamps on opposite sides of a cutoff, and belong to the same rollup bucket. The policy computes its cutoff using now:

Policy Base PR
Time >= cutoff No rows Returns a rolled-up timestamp below the cutoff, value 2
Time <= cutoff Rolled-up value 3 Rolled-up value 1
SET optimize_on_insert = 0;
SET apply_row_policy_after_final = 1;
SET explain_query_plan_default = 'legacy';
CREATE TABLE g (Path String, Time DateTime('UTC'), Value Float64, Version UInt32)
ENGINE = GraphiteMergeTree('graphite_rollup') ORDER BY (Path, Time) SETTINGS index_granularity=8192;
INSERT INTO g VALUES ('sum_1', 960000100, 1, 1), ('sum_1', 960000200, 2, 1);
CREATE ROW POLICY p ON g USING Time >= if(now() > toDateTime('2000-01-01'), toDateTime(960000150, 'UTC'), toDateTime(0, 'UTC')) TO ALL;
SELECT 'deferred', count() FROM (EXPLAIN actions=1 SELECT * FROM g FINAL) WHERE explain LIKE '%Deferred row level filter%';
SELECT 'rows', toUnixTimestamp(Time), Value, Version FROM g FINAL;
DROP ROW POLICY p ON g;
CREATE ROW POLICY p ON g USING Time <= if(now() > toDateTime('2000-01-01'), toDateTime(960000150, 'UTC'), toDateTime(0, 'UTC')) TO ALL;
SELECT 'le', toUnixTimestamp(Time), Value, Version FROM g FINAL;
DROP ROW POLICY p ON g;
DROP TABLE g;

The smallest sound fix also simplifies the design: share the existing engine-aware getSortingKeyNamesSafeBeforeFinal with the row-policy path. It already accounts for Graphite and permits its path column only when that column leads the sorting key. Add regression coverage for both timestamp and non-leading-path policies.

There is another small cleanup: the explicit allColumnFunctions check at lines 225–228 duplicates what allNodeFunctions already does for constant columns. Remove that duplicate, but keep the new mutable-set check.

GraphiteMergeTree rolls up rows with different times into one row with a
rounded time, so a policy over the time column does not give every row of a
rollup group the same verdict, and a path policy can make rows of one path
adjacent unless the path leads the sorting key. The row-policy check now uses
getSortingKeyNamesSafeBeforeFinal, which PREWHERE already uses and which
admits only the leading path column for Graphite. This also keeps a literal
time policy on a Graphite table after FINAL, as apply_row_policy_after_final
promises.

Remove the allColumnFunctions check in isNodeDeterministic: allNodeFunctions
already applies it to a COLUMN node.

Requested in review by @ yariks5s.

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

Copy link
Copy Markdown
Collaborator Author

Thanks, I reproduced both rows of your table on the PR head. Fixed in 5c76124:

  • isRowPolicyDeferredAfterFinal now takes its columns from getSortingKeyNamesSafeBeforeFinal, now declared in MergeTreeWhereOptimizer.h. Your repro gives the base result again: the policy is deferred, Time >= cutoff returns no rows and Time <= cutoff the rolled-up value 3.
  • 05616 got four Graphite cases: a now() time policy, a literal time policy and a now() path policy on ORDER BY (Time, Path) stay after FINAL; a now() policy on the leading path still runs before it. The previous head fails the three deferred cases. The new head passes 50/50 with random settings, and 10/10 each with parallel replicas (both parallel_replicas_local_plan values) and serialize_query_plan = 1.
  • Removed the duplicate allColumnFunctions check; the Set table check stays.

One effect beyond the regression: a literal time policy on a Graphite table, which master applies before the rollup, now runs after it too, so Time <= toDateTime(960000150, 'UTC') returns the rolled-up 3 instead of 1. The PR description and the apply_row_policy_after_final description now say this.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5c76124

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
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Query builder not found for text search query with function 'A (STID: 3694-54bc) not from this PR: the fuzzer ran SELECT count() FROM tab__fuzz_484 FINAL PREWHERE '0.000100' = str WHERE str = 'bar', a lazy FINAL read with different PREWHERE and WHERE predicates on a text-indexed column. Master aborts on the same shape; this error was in the AST fuzzer runs of 2 other PRs in October, before this PR #121041 (mine, open)
PR praktika rollup of the row above #121041 (mine, open)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261112-200351

@fm4v
fm4v added this pull request to the merge queue Nov 13, 2026
Merged via the queue into ClickHouse:master with commit acd88ab Nov 13, 2026
203 of 205 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 13, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 13, 2026
yariks5s added a commit that referenced this pull request Nov 13, 2026
…d the deferral that this PR removes
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 22, 2026
Query #0 measured FINAL over a ReplacingMergeTree whose part layout was a
race: perf.py stops merges only after both servers are filled, so each
server keeps whatever its background merges reached, and the FINAL plan
(and its time) follows the layout. On master since the test was added
the two servers of a job ran different plans in 37% of amd jobs and 13%
of arm jobs, and 98% of those differ by more than 10%.

Disable #0 (query freeze) and append its copy on a new table that stops
its merges before the INSERTs and pins the blocks (single-threaded,
375000-row blocks, no squashing), so every server reads the same 32 parts
of 93750 rows, 8 per partition; a throwIf on system.parts fails the setup
if that layout ever changes. INSERT parts of ReplacingMergeTree are
written at level 1 (optimize_on_insert), hence max(level) = 1.

With 8 parts in every partition FINAL merges each partition fully, so
the query still shows the gain of ClickHouse#130536 (row policy applied before
FINAL): locally 4.8-6.0x time and 7.9-8.1x memory against the build
before it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 23, 2026
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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

26.10: FINAL query on a table with a currentUser() row policy uses ~10x more memory (regression from #117248)

5 participants