Skip to content

Execute IN and EXISTS subqueries of mutations on the initiator with mutations_execute_subqueries_on_initiator - #129611

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:mutations-execute-in-exists-subqueries-on-initiator
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:mutations-execute-in-exists-subqueries-on-initiator

Conversation

@groeneai

@groeneai groeneai commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

With mutations_execute_subqueries_on_initiator = 1, the subqueries of IN and EXISTS in ALTER TABLE ... UPDATE/DELETE and DELETE FROM are executed when the mutation is submitted and stored as their results, so the mutation no longer depends on the tables they read. A mutation like ALTER TABLE t DELETE WHERE k IN (SELECT k FROM tmp) now completes after tmp is dropped, instead of failing on every part and holding back all later mutations of t. Before, only scalar subqueries were executed on the initiator.

Description

Related: #37435

A mutation stores its IN (SELECT ... FROM tmp) operand as text and builds the set again for every part. Once tmp is dropped every attempt fails with UNKNOWN_TABLE, and since mutations apply in order, no later mutation of the table is applied. mutations_execute_subqueries_on_initiator snapshots subqueries at submission, but only scalar ones.

With the setting on, the subquery of IN is executed and replaced with (SELECT arrayJoin(_CAST([...], 'Array(T)'))) (untuple for several columns), and exists(...) with _CAST(0|1, 'UInt8'), computed as SELECT 1 FROM (subquery) LIMIT 1. It stays a subquery, not a literal set, because the two set kinds convert in opposite directions: s IN (SELECT 1) matches '01', s IN [1] does not. Decimal, DateTime64 and Time64 values are written as Decimal(76, S) and cast back, since their own types do not read all values back from text (a DateTime64 before 1973). The subquery is kept (current behaviour) when it names an alias defined outside it, or its result exceeds mutations_max_literal_size_to_replace, 1,000,000 rows or an array of 1,000,000 elements, holds a NaN or a decimal of more than 76 digits, or has a Variant, Dynamic, JSON or QBit type. Identical subqueries of a command share one result.

Not changed: the setting's default; IN <table> and Set/Join tables (the issue's case, hence Related); the determinism check still sees the IN operand as a subquery, so ReplicatedMergeTree needs allow_nondeterministic_mutations and apply_mutations_on_fly does not apply it, while a materialized exists, a constant, does not need it. A result over the limit is read only up to it (an aggregating subquery runs in full).

Validation: the new test fails on master (Code: 341 ... UNKNOWN_TABLE ... (UNFINISHED)) and passes with the fix in 50 randomized, 50 plain and 10 DatabaseReplicated runs.

Category Improvement: the setting covered only scalars, and defaults are unchanged.


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

groeneai and others added 6 commits November 5, 2026 13:42
A mutation stores the subquery of `IN` as text and builds the set again
for every part, so `ALTER TABLE t DELETE WHERE k IN (SELECT k FROM tmp)`
fails with UNKNOWN_TABLE on every attempt once `tmp` is dropped (or when
`tmp` is a session temporary table). Mutations finish in order, so every
later mutation of `t` is never applied either. The setting
`mutations_execute_subqueries_on_initiator` snapshots subqueries when the
mutation is submitted, but `ExecuteScalarSubqueriesVisitor` skips the
subqueries of `IN` and `exists` on purpose, so it covered scalars only.

With the setting on, a new mutation-only visitor in
MutationsNonDeterministicHelpers.cpp runs after the scalar one:

- The subquery of every `IN` operator is executed with
  `interpretSubqueryWithAnalyzer` (the path `ActionsVisitor` uses for
  `IN`) and replaced with `(SELECT arrayJoin(_CAST([...], 'Array(T)')))`,
  wrapped in `untuple` for several columns. It stays a subquery and is not
  turned into a literal set, because a set from a subquery casts the left
  argument to the subquery's types, while a set from literals converts the
  literals to the left type: `s IN (SELECT 1)` matches '01',
  `s IN [1]` does not.
- `exists(subquery)` becomes `_CAST(0|1, 'UInt8')`. Only
  `SELECT 1 FROM (subquery) LIMIT 1` is executed, as the analyzer does, so
  unused projections are not computed. Being a constant, it also no longer
  trips the ReplicatedMergeTree determinism check.
- The subquery is kept when its result has a Variant, Dynamic or JSON
  type (their values do not round-trip through a literal), or does not fit
  `mutations_max_literal_size_to_replace`. Pulling stops as soon as the
  rows or bytes exceed the limit (zero-byte columns such as `Tuple()` are
  bounded by rows) or the rows exceed the 1M elements `ColumnArray::get`
  allows, so a large set never builds a `Field`.
- All occurrences of one subquery in a command reuse the first result, as
  they share one set today.

The progress and interactive cancel callbacks are wired as in the scalar
path, so KILL QUERY stops a long subquery at submission. The default of
the setting is unchanged; `IN <table>` and Set/Join tables are not covered.

Related: ClickHouse#37435

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The description of `mutations_execute_subqueries_on_initiator` now also
names the 1000000-row bound, which decides when
`mutations_max_literal_size_to_replace` is raised.

The test gets two oracles that the previous arms could not fail:
- Two occurrences of `IN (SELECT rand64())` in one command must store
  the same literal, so executing the subquery once per occurrence is
  caught.
- Two `IN` subqueries over `numbers(2000000)` that throw past one million
  rows must be accepted, so reading the whole result before checking the
  limit is caught, and for `Tuple()` (no bytes) so is dropping the
  `rows <= mutations_max_literal_size_to_replace` bound.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The 1,000,000-row bound of the `IN` result is now test-proven in both
directions. Under a raised `mutations_max_literal_size_to_replace` only
that bound stops reading, so:
- a subquery that throws at row 999000 must fail at submission, which
  catches a lower bound;
- a subquery that throws at row 1200000 must be accepted and kept, which
  catches checking the bound only after reading the whole result.

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

Two fixes in the initiator-side execution of `IN` subqueries of mutations:
- The per-command cache keyed a subquery by its AST hash with aliases
  ignored. Aliases change what an identifier resolves to, so two
  subqueries that differ only in alias names can return different
  results, but they shared one. The key now includes aliases, matching
  the two sets the mutation builds when the subqueries are kept.
- `ColumnArray::get` refuses to build a field of an array with more than
  1000000 elements, so a result with such a nested array threw
  `TOO_LARGE_ARRAY_SIZE` at submission. Such a result now keeps the
  subquery, like a result of more than 1000000 rows.

The new alias arm compares the updated keys with `arraySort`: on a sparse
column read in order `groupArray` puts the default values last (ClickHouse#123817).

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

The test now proves that subqueries with aliases and `Array` results up to
the limit are executed on the initiator:
- An `Array(UInt32)` column `IN` a subquery whose table is dropped before
  the mutation runs: the stored command holds the materialized set and
  the mutation finishes.
- The two subqueries that differ only in their aliases are both replaced
  in the stored command, with two different results.

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

The field of a `QBit` value is its internal tuple of bit planes, which
`CAST` cannot turn back into `QBit`, so with
`mutations_execute_subqueries_on_initiator` an `IN` subquery with a `QBit`
result made the `ALTER` fail at submission with `TYPE_MISMATCH`. Such a
subquery is now kept, like one with a `Variant`, `Dynamic` or `JSON`
result.

The test now checks that `IN` subqueries with `Dynamic`, `JSON` and `QBit`
results are kept as text and that the mutations match the same rows as
with the setting disabled.

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

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (rounds 1-6): 11 findings, 9 fixed, 2 not changed
Finding Verdict
❌ Two subqueries that differ only in their aliases (and so resolve to different columns) shared one cached result, so the mutation touched other rows than with the setting off Agreed, fixed: the cache key includes aliases; a test compares such a pair with the setting on and off
⚠️ A result holding an array of more than 1,000,000 elements failed the ALTER with TOO_LARGE_ARRAY_SIZE instead of keeping the subquery Agreed, fixed: such a result keeps the subquery; covered by the test and the setting description
⚠️ No test arm materialized an Array result, so a check that kept every array would have passed Agreed, fixed: an Array(UInt32) IN subquery must be stored as its result and the mutation must complete after its source table is dropped
⚠️ The alias test compared only rows, so keeping alias-bearing subqueries as text would have passed Agreed, fixed: the stored command must hold two different literal sets
❌ A QBit result was materialized although its value cannot be cast back from the literal, so the ALTER failed with TYPE_MISMATCH when the setting was on Agreed, fixed: a QBit result keeps the subquery, like Variant, Dynamic and JSON; covered by the test and the setting description
⚠️ Only the Variant fallback was tested, so dropping the Dynamic or JSON check would have passed Agreed, fixed: Dynamic, JSON and QBit IN subqueries must be stored as text and the mutations must complete
⚠️ The setting description omitted the 1,000,000-row bound that keeps the IN subquery Agreed, fixed: the bound is in the setting description and the PR body
⚠️ The test did not prove that one subquery is executed once per command, or that reading stops at the limit Agreed, fixed: identical rand64() subqueries must store one literal; subqueries that throw past the limit must be accepted
⚠️ The 1,000,000-row bound itself was not shown to stop reading Agreed, fixed: at a raised limit a subquery that throws at row 999000 must fail and one that throws at row 1200000 must be accepted
⚠️ A materialized IN is still rejected by apply_mutations_on_fly Not changed: every subquery mutation is rejected on fly, as on master (AlterConversions.cpp); stated in the PR body
❌ In a Replicated database the ALTER is queued before the rewrite, so a session temporary table is not visible to the replica that runs it Not changed: the ALTER is rejected at submission with UNKNOWN_TABLE and no mutation is created, as on master (the predicate is resolved in the same worker context); rewriting before queueing would change what every queued mutation stores, a separate change

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. ALTER TABLE t DELETE WHERE k IN (SELECT k FROM tmp) SETTINGS mutations_execute_subqueries_on_initiator = 1, DROP TABLE tmp, then any ALTER ... SETTINGS mutations_sync = 2: master fails every time with Code: 341 ... UNKNOWN_TABLE ... (UNFINISHED).
b Root cause explained? The IN operand is stored as text and resolved again for every part, so the mutation depends on tmp living until it finishes. The initiator-side rewrite of mutations_execute_subqueries_on_initiator replaced only scalar subqueries and skipped the subqueries of IN and exists.
c Fix matches root cause? Yes. The operand is snapshotted where the command is rewritten before it is persisted; no error classification or retry change.
d Test intent preserved / new tests added? New SQL test covering predicate, assignment, several columns, a repeated subquery, DELETE FROM, exists, a parity check against the subquery executed by the mutation, the size, row and type fallbacks, an Array result materialized before its source table is dropped, a nested array of more than 1,000,000 elements kept as a subquery, Dynamic, JSON and QBit results kept as subqueries with the same rows updated as with the setting off, one result reused per command, two subqueries that differ only in their aliases both executed to two different stored results, reading stopped at the limit and at 1,000,000 rows, and ReplicatedMergeTree. Existing tests unchanged.
e Both directions demonstrated? Master: FAIL 3/3 (UNFINISHED). Fix: 50/50 randomized, 50/50 plain, 10/10 DatabaseReplicated. Each fallback (incl. the nested-array one and the Dynamic, JSON and QBit type guards), the Array materialization, the reuse, the alias-sensitive reuse key, the execution of subqueries with aliases and the early stop are shown by a mutated build that makes the test fail.
f Fix is general across code paths? Every IN operator (incl. GLOBAL, NOT, nullIn), exists, predicates and assignments, DELETE FROM. IN <table> and Set/Join tables are not covered and are stated in the description.
g Fix generalizes across inputs (params/datatypes/wrappers)? Setting 0 vs 1 give equal results for Nullable/NULL with NOT IN, LowCardinality, LC(Nullable), Tuple, Array, Map, Decimal, DateTime with a time zone, Float NaN/-0, escaped String, UUID/IPv6, Enum/FixedString, empty sets and aliases. Variant/Dynamic/JSON/QBit stay subqueries.
h Backward compatible? (maintainer-approved exception only) Default unchanged. The stored command is plain SQL that older versions parse. Only users who enabled the setting see the snapshot, which is what the setting describes.
i Invariants and contracts preserved? The set keeps the subquery's types (a literal set would convert to the left type). exists keeps its UInt8 type. The executor stops before the pipeline is destroyed, KILL QUERY cancels the submission, and access checks match the setting-off path.

Session id: cron:clickhouse-impl-slot-6:20261105-125400

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @scanhex12, could you review this and add the can be tested label so CI runs? With mutations_execute_subqueries_on_initiator = 1 the subqueries of IN and exists are now executed at submission and stored as their results, so ALTER TABLE t DELETE WHERE k IN (SELECT k FROM tmp) no longer fails on every part once tmp is dropped (#37435).

@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5fe7ab2]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR extends mutations_execute_subqueries_on_initiator to snapshot IN and EXISTS subqueries when mutations are submitted. No unresolved findings remain at head 5fe7ab2c8472b2687989e5486ae6a5749499f9e3. The earlier timestamp round-trip and surrounding-alias findings are fixed, and both review threads have been resolved.

The complete new stateless test passed against this head's Fast test binary with local Keeper, matching the reference exactly, including the ReplicatedMergeTree arm. Additional comparisons with the setting disabled and enabled passed for 32 valid cases covering numeric limits, timestamps, dates, nested types, and aggregate values.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements can be tested Allows running workflows for external contributors comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). labels Nov 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 5fe7ab2c8472b2687989e5486ae6a5749499f9e3 with master failed: LogClusterNotReady: the endpoint never became ready.

See the job log for details.

… using outer aliases

The literal of an executed `IN` subquery is stored as text and parsed again by
the mutation. A `DateTime64` or `Time64` value is written as its decimal number
of seconds, which those types do not read back for every value: a `DateTime64`
before 1973-03-03 or after 2286 became NULL (so `d NOT IN (...)` deleted rows it
should keep) or failed the ALTER with CANNOT_PARSE_DATETIME, a negative `Time64`
failed it with CANNOT_PARSE_TEXT, and a `Decimal` value beyond its precision
(e.g. a sum of two `Decimal(9, 2)` values) failed it too. Such leaves are now
written as `Decimal(76, S)`, which reads back any value of up to 76 digits, and
the literal is cast back to the result type. The literal stays one array
literal, so its size and the cost of parsing it do not change (a 999000-element
`DateTime64` set at a raised limit: same time and memory as before;
`columnConstantToExactLiteralAST` would build one function per element and
fails such sets from 50000 elements with "Query tree is too big").

Two values have no text that reads back, so their subquery is kept: a NaN, whose
payload `IN` compares (`0 / 0` is a NaN with the sign bit set, while `nan` reads
back without it, so the mutation skipped rows it updates with the setting off),
and a `Decimal256` value of more than 76 digits, which arithmetic can produce.
The values are checked after `LowCardinality` is removed, because a shared
dictionary is not a subcolumn and one read from an old part can hold any NaN.

A subquery that names an alias defined outside it, e.g.
`WHERE (toUInt64(1) AS a) = 1 AND k IN (SELECT a)`, cannot be executed on its
own, so the ALTER failed with UNKNOWN_IDENTIFIER while it works with the
setting off. Such subqueries of `IN` and `exists` are now kept.

Reported by the AI review on the PR and by a second-model review.

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

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5fe7ab2

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
Build profile diff infra, not from this PR (no ci/ file in the diff): all 8 readiness probes SELECT 1 to the CI logs cluster hit Read timed out. (read timeout=3), so has_pr_data raised LogClusterNotReady: the endpoint never became ready. The same red hit 8 PRs between 2026-11-06 00:00Z and 02:52Z. The merged #128067 covers only a probe the server answers with a load error, and it is on this branch a fix task is created (investigating at full effort, fixing-PR link to follow here)
PR praktika rollup of the row above a fix task is created (the one for the row above)

The Config Workflow / Pre Hooks failure in CIDB comes from the run on the previous head 19f2f2f before the can be tested label. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261106-033003

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Build profile diff LogClusterNotReady red (readiness probe read timeouts) created: #129675

qoega pushed a commit to qoega/ClickHouse that referenced this pull request Nov 19, 2026
… logs cluster outage

When the read-only sub-service of the CI logs cluster stops answering,
every `SELECT 1` readiness probe of `LogCluster.select` raises
`requests.exceptions.ReadTimeout`. `is_ready` turned that into a bare
False without a `probe_error`, so `select` raised `LogClusterNotReady`,
which `build_profile_diff_job.main` does not catch, and the check went
red on unrelated PRs (8 of them on 2026-11-06 between 00:00Z and 02:52Z,
e.g. job 127646247697 of ClickHouse#129611). The same outage hitting a POST already
ends `LogClusterUnavailable` (ClickHouse#121048), and so does a probe the server
rejects with 241 (ClickHouse#128067).

A probe that raises `ReadTimeout` now records `LogClusterUnavailable` in
`probe_error`, and the tail added by ClickHouse#128067 reports the read green as
"the endpoint never became ready: the readiness probe timed out: ...".
The last probe decides, as there.

A `ReadTimeout` (requests 2.33.0, the CI pin) is raised only after the
name resolved and a server accepted the connection: a stalled TLS
handshake or a stalled answer. Connection refused, an unresolvable name,
no SYN-ACK and a certificate mismatch raise `ConnectionError`
(`ConnectTimeout` and `SSLError` are subclasses), and the server itself
rejects a rotated password with 516. All of those, a missing secret and
a gateway answer still end `LogClusterNotReady`, as ruled on ClickHouse#120288.

This is the `SELECT 1`-timeout leg left open on ClickHouse#121048. Validated with
a throwaway harness against master (real sockets, mocked transport and
`main()` end to end); only the probe-timeout cases change. No test is
committed for the CI scripts (ClickHouse#119766).

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

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

can be tested Allows running workflows for external contributors comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant