Repository navigation
Conversation
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]>
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).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20261110-145400 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20261110-140200 |
|
cc @yariks5s @antaljanosbenjamin, could you review this and add the |
|
Workflow [PR], commit [5c76124] Summary: ❌
AI ReviewSummaryThis PR restores row-policy filtering before Final VerdictStatus: ✅ Approve. No new inline findings. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units10 translation units recompiled, 66 s compile time in total, 10 of them have a recent master baseline. |
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]>
…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]>
yariks5s
left a comment
There was a problem hiding this comment.
@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]>
|
Thanks, I reproduced both rows of your table on the PR head. Fixed in 5c76124:
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 |
CI finish ledger - 5c76124Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261112-200351 |
acd88ab
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]>
Closes: #130317
Related: #117248
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A
FINALquery on a table whose row policy comparesORDER BYcolumns with a value computed once per query, such ascurrentUser(),now()or anIN (subquery)set, applies the policy before the merge again, as in 26.8, instead of reading and merging every row first. OnGraphiteMergeTreethis holds only for a policy on the path column when it leadsORDER BY. Closes #130317.Description
Since 26.9 a row policy like
c2 = substring(currentUser(), 1, 3)on anORDER BYcolumn is applied afterFINAL, 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 usingnow(),currentDatabase()orIN (subquery)are deferred too.#117248 added
node->isDeterministic()toisNodeDeterministic, the gate ofisRowPolicyDeferredAfterFinal. For aCOLUMNnode it returnsis_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 bodyallNodeFunctionschecks (05141, 05182), and the set of aSettable, also when a lambda captures it, which a concurrentINSERTchanges 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).GraphiteMergeTreerolls up rows with different times, so the check now takes its columns fromgetSortingKeyNamesSafeBeforeFinal, as PREWHERE does: only a policy on the path column, when it leadsORDER 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_constantfails on master (the policy is deferred) and passes 50/50 with random settings, in the parallel-replicas flavour and withserialize_query_plan = 1. New performance testfinal_row_policy_query_constant. On the master release build with the issue's data, thecurrentUser()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 withcompatibility = '24.0'(medians of 10).🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/130536]
Version info
26.11.1.2151-master(included in26.11and later)