Skip to content

Fix a crash when a CHECK constraint's scalar subquery reads a Distributed table - #121418

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/scalar-subquery-analyzer-distributed-crash
Sep 24, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/scalar-subquery-analyzer-distributed-crash

Conversation

@groeneai

@groeneai groeneai commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #107653
Related: #120311
Related: #121464

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

Fixed a server crash when a scalar subquery inside a standalone expression, such as a CHECK constraint or a TTL expression, reads a Distributed table or the remote table function.

Description

On 26.8 a plain statement kills the server, through the same unguarded dereference:

CREATE TABLE t (x UInt64, CONSTRAINT c CHECK x < (SELECT max(id) + 1000
    FROM remote('127.0.0.1', currentDatabase(), 'src'))) ENGINE = MergeTree ORDER BY tuple();

Found by the AST fuzzer on my PR #121280: Stress test (arm_tsan), Segmentation fault (STID: 3422-39ed), report.

TreeRewriter still runs the scalar subquery of a standalone expression through InterpreterSelectWithUnionQuery, which yields a SelectQueryInfo with no query tree and no planner context, while StorageDistributed::read dereferences query_info.planner_context unconditionally. The branch that hid that was dead once allow_experimental_analyzer was frozen at 1 (#118629), and #120311 removed it; that PR's note in InterpreterSelectQuery.h asks new callers to use InterpreterSelectQueryAnalyzer. The identical dereference was reached before through a materialized view and fixed at its origin by #107653, so I fixed the producer rather than guarding one storage.

The swap carries over the setup of the analyzer's own scalar executor: view-source substitution through the storage overload, parallel replicas off, the insertion-table structure hint suppressed, and forced CTE materialization. Pinning parallel replicas on the context is not enough, since the query tree builder re-applies a SETTINGS clause written inside the subquery over the node context the planner reads, so both spellings of that setting are stripped from a clone. usesViewSource() does not exist on the analyzer interpreter, so both call sites now ask the built query tree.

Once the crash is gone the same statement reaches the next defect on that path. A standalone expression is analysed with the global context - StorageFactory hands the storage args.getContext(), which never went through Context::makeQueryContext and so carries a zero client version - and RemoteQueryExecutor::sendQueryUnlocked rejects a shard query with an unknown initiator version. It stays invisible while the shard is local, which test_shard_localhost is, so the public run reads it without RemoteQueryExecutor; the private sync caught it in Stress test (arm_asan_ubsan, meta in keeper) (STID: 4148-3044). The subquery context now reports this server's own version, exactly as Context::makeQueryContext does for the other server-initiated queries and DDLTaskBase::makeQueryContext does for a replayed DDL, and a new test case pins the network path with prefer_localhost_replica = 0.

Validated both directions (gdb, then the new test on unpatched and patched servers), 100/100 randomized and plain runs, and an A/B sweep of 172 neighbouring tests with no new failure.

Also noticed and left alone, both identical without the fix: an INSERT into a table with such a constraint fails with UNKNOWN_IDENTIFIER, and such a table using remote(...) fails to load at startup with THERE_IS_NO_QUERY; #96886 rewrites that code. The test therefore drops the table carrying the remote(...) constraint as soon as its DETACH/ATTACH check is done, so that a stress-test restart does not land on it.


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

Version info

  • Merged into: 26.10.1.573-master (included in 26.10 and later)

… Distributed table

A `CREATE TABLE` whose `CHECK` constraint contains a scalar subquery over a
`Distributed` table or `remote(...)` kills the server:

    CREATE TABLE t (x UInt64, CONSTRAINT c CHECK x < (SELECT max(id) + 1000
        FROM remote('127.0.0.1', currentDatabase(), 'src'))) ENGINE = MergeTree ORDER BY tuple();

`InterpreterCreateQuery::getConstraintsDescription` analyses every constraint with
`TreeRewriter::analyze`, which runs `executeScalarSubqueries`; that visitor built
`InterpreterSelectWithUnionQuery` unconditionally, and the old interpreter never
assigns `query_info.query_tree` or `query_info.planner_context`. Since
`StorageDistributed::read` has no non-analyzer arm any more, it dereferences the
planner context unconditionally and the read faults on a null pointer.

A `TTL ... WHERE` predicate is a second carrier of the same fault, not a separate bug:
`TTLDescription::getTTLFromAST` analyses the `DELETE WHERE` predicate through the same
`TreeRewriter::analyze` (`TTLDescription.cpp:1490` then `:1270`), so the one fix resolves
both slots. The two differ in how the source may be named: the `remote(...)` table
function is rejected before planning there with `THERE_IS_NO_QUERY`, because a TTL
description is built without a query context and resolving a table *function* needs one,
so only a named `Distributed` table reaches the dereference. Both slots are covered by the
new test, the `TTL` one through a named table.

The branch that used to hide this was keyed on `allow_experimental_analyzer`, which has
been frozen at 1 since ClickHouse#118629, and ClickHouse#120311 removed it. That commit's own note in
`InterpreterSelectQuery.h` asks new callers to use `InterpreterSelectQueryAnalyzer`; a
scalar subquery of a standalone expression is the user's own `SELECT`, i.e. exactly that
case. The crash is not a regression of ClickHouse#120311: the same dereference and the same
interpreter construction exist on 26.9 and 26.8, where that setting's default of 1 selects
the analyzer arm as well.

The identical dereference was reached once before through `StorageMaterializedView` and
fixed at its origin by ClickHouse#107653. This is a second entry path, so the producer is fixed
rather than the storage: a null guard in `StorageDistributed` would have no arm to fall
back to and could only throw, turning a crash into a rejected statement that works on
26.9, and it would have to be repeated for every analyzer-only engine.

The interpreter swap carries over four behaviours of the old path, each matching the
analyzer's own scalar-subquery executor in
`src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp`:

* the materialized-view source substitution `JoinedTables::getLeftTableStorage` did,
  through the `InterpreterSelectQueryAnalyzer` storage overload, so a scalar subquery
  compiled during a view push still reads the inserted block;
* `use_structure_from_insertion_table_in_table_functions` in the subquery settings,
  because `QueryAnalyzer` reads it from the scope context rather than from the query
  context the pre-existing line mutates (that line stays, it is issue ClickHouse#52494's);
* `allow_experimental_parallel_reading_from_replicas = 0`, because `Planner`'s
  constructor inspects the tree for parallel-replica candidates;
* `options.forceMaterializeCTE()`, because `collectMaterializedCTEs` returns nothing for
  subquery options, so a materialized CTE would be read unpopulated.

Disabling parallel replicas on the subquery context alone is not enough, and the setting is
also stripped from a clone of the subquery AST. `QueryTreeBuilder::buildSelectExpression`
applies a SELECT's own `SETTINGS` clause onto the context it stamps on the `QueryNode`, and
`findQueryForParallelReplicas` reads the decision from that node context inside `Planner`'s
member-init list, i.e. inside the interpreter's constructor, where nothing can repair it
afterwards. Without the strip, a scalar subquery whose own clause turns parallel replicas on
and names a cluster that does not exist is rejected with `CLUSTER_DOESNT_EXIST` where it used
to succeed: measured on the constraint above with
`parallel_replicas_for_non_replicated_merge_tree = 1` in the same clause. Both spellings of the
aliased setting are stripped, the way the automatic-parallel-replicas probe in
`InterpreterSelectQueryAnalyzer` strips the settings it overrides, and from a clone because the
AST belongs to the statement being analysed rather than to this helper.

The test's session-level arm pins `automatic_parallel_replicas_mode = 0`, which is that
setting's own default. The test runner draws 2 for it in a quarter of runs, and with the
statement's `allow_experimental_parallel_reading_from_replicas = 1` inherited,
`InterpreterSelectQueryAnalyzer::buildContext` then clears `enable_parallel_replicas` on its
own context copy, so the subquery would never reach a cluster lookup and the arm would stop
exercising the strip at all in those runs.

The recursive nested-context walk the reference executor also does stays uncopied: it clones an
already-built tree whose nested nodes carry the original context, while this path builds the
tree from an AST with the subquery context, and `QueryTreeBuilder` stamps a copy of that context
onto every node it creates.

`usesViewSource()` lives on `IInterpreterUnionOrSelectQuery` and has no counterpart on
the analyzer interpreter, so both call sites ask the built query tree with the existing
`isStorageUsedInTree`. The answer is the same wherever the old flag was true and
conservative elsewhere: a scalar can only move from the global cache to the per-query
one, never the reverse.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Sep 21, 2026
@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; 5 findings over 4 rounds, 4 raised by
the gate engine and 1 by the reviewing pass itself; the fourth gate round returned none). Bounded:
one full pass per round plus delta rechecks.

# Sev Finding Verdict Evidence / action
1 ❌ A SETTINGS clause written inside the scalar subquery re-enabled parallel replicas, so a statement master accepts could be rejected (getQueryInterpreter) AGREE, fixed in this PR The suppression was written only onto the interpreter context, while findParallelReplicasQuery.cpp:365 reads the query node's context, which QueryTreeBuilder.cpp:314-318 builds from the subquery's own clause. Both spellings of the setting are now stripped from a clone of the subquery, and an arm whose inner SETTINGS names a cluster that exists nowhere covers it
2 ⚠️ The session-level parallel-replica arm could pass even with the inherited suppression removed, because it named the configured parallel_replicas cluster and value 1 disables silently on failure AGREE, fixed in this PR That cluster lists 127.0.0.1 among its replicas in tests/config/config.d/clusters.xml, so the local INCONSISTENT_CLUSTER_DEFINITION signal does not exist in CI. The arm now names a cluster defined nowhere, and the mutant with the suppression deleted fails it with CLUSTER_DOESNT_EXIST in any configuration
3 ⚠️ No arm covered a TTL slot, although the changelog entry names TTL expressions AGREE, fixed in this PR buildExpressionAndSets (TTLDescription.cpp:1289) serves both the expiry expression (:1463) and the DELETE WHERE predicate (:1490), and both reach the same producer through TreeRewriter::analyze (:1270). Measured on both binaries: the expiry slot rejects a subquery outright (Code: 36) and remote() in a TTL slot dies at THERE_IS_NO_QUERY before reaching the storage, but a TTL ... WHERE predicate reading a named Distributed table crashes the unpatched server through the same frames. That is now an arm, so the entry's TTL clause is backed rather than narrowed
4 ⚠️ The session-level arm's oracle is not deterministic: with automatic_parallel_replicas_mode randomized to 2, deleting the suppression no longer reaches the cluster error AGREE, fixed in this PR tests/clickhouse-test:1935 picks mode 2 in 25% of randomized runs, and InterpreterSelectQueryAnalyzer::buildContext then clears enable_parallel_replicas itself, so the mutant passes and the arm silently stops discriminating. The arm now pins automatic_parallel_replicas_mode = 0, and the mutant is required to fail with CLUSTER_DOESNT_EXIST with that mode forced to 2 as well, not merely under the runner's default dice
5 ⚠️ The commit message claimed this fixes the last remaining producer of a tree-less SelectQueryInfo, on the premise that the sibling interpretSubquery producers are reachable only from the old InterpreterSelectQuery. That premise is false AGREE, fixed in this PR A CHECK constraint's DAG is built by the three-argument ExpressionAnalyzer (ConstraintsDescription.cpp:174-176), which allocates its own PreparedSets (ExpressionAnalyzer.cpp:205-210), so ActionsMatcher::makeSet does not early-out and ActionsVisitor.cpp:1875 reaches interpretSubquery with no InterpreterSelectQuery above it. The superlative is deleted rather than defended, and I make no claim about that sibling's behaviour, which I did not measure. The scope this PR does claim, scalar subqueries of standalone expressions, is unchanged and fully tested

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Noted and not blocking:

  • The create_table_query assertion of the inner-SETTINGS arm cannot fail on its own (an in-place
    strip is invisible there, because the constraint's stored AST is a second, un-analysed clone), so it
    is invariance coverage rather than a discriminating oracle; the discriminating oracle for the same arm
    is its first assertion.
  • A shard/distributed tag was considered for the new test and deliberately not added: 151 of the 296
    stateless tests that create ENGINE = Distributed carry no such tag, including every recent one, and
    tests/config/install.sh installs clusters.xml for every flavour.
  • The changelog entry names two slots and two sources, and one of the four combinations is not a
    carrier: remote() inside a TTL slot fails earlier, identically with and without this change. The two
    real carriers each have an arm.
  • Two of the four carried-over behaviours, the insertion-table structure hint and
    forceMaterializeCTE(), rest on parity with the analyzer's own scalar-subquery executor plus the
    neighbouring structure_from_insertion and materialized_cte batches passing identically on both
    arms. I found no statement that reddens without them, and I say so rather than implying coverage.

Session id: cron:clickhouse-review-slot-8:20260921-183300

@clickhouse-gh clickhouse-gh Bot closed this Sep 21, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, one statement, 3/3, no randomization or sanitizer needed: CREATE TABLE t (x UInt64, CONSTRAINT c CHECK x < (SELECT max(id) + 1000 FROM remote('127.0.0.1', 'default', 'src'))) ENGINE = MergeTree ORDER BY tuple() against a master build. clickhouse local is enough; the crash happens during planning.
b Root cause explained? InterpreterCreateQuery::getConstraintsDescription analyses every CHECK with TreeRewriter, which executes the scalar subquery through InterpreterSelectWithUnionQuery. That interpreter never fills query_info.query_tree/planner_context, and StorageDistributed::read dereferences the planner context unconditionally (StorageDistributed.cpp:893 then :773). Verified under gdb: si_addr = 0x0, both members null.
c Fix matches root cause? The producer is changed to InterpreterSelectQueryAnalyzer, which is what InterpreterSelectQuery.h:40-51 asks new callers to use. No null guard at the crash site: post-#120311 there is no AST arm to fall back to, so a guard could only throw, turning a crash into valid input rejected. Parallel replicas are disabled for the subquery both on its context and by stripping the setting from a clone of its AST, because QueryTreeBuilder would otherwise re-apply a SETTINGS clause written inside the subquery over the node context the planner reads.
d Test intent preserved / new tests added? New tests/queries/0_stateless/05234_constraint_scalar_subquery_over_distributed.{sql,reference}, covering both standalone-expression slots that reach the producer: a CHECK constraint (creation, metadata reload, and an execution-sensitive throwIf probe) and a TTL ... WHERE predicate over a named Distributed table. No existing test relaxed, and the neighbouring scalar-subquery, materialized-view, materialized-CTE, mutation-set and TTL-WHERE-with-subquery tests pass (#107653's 04338_materialized_view_over_distributed_old_analyzer_crash was deleted upstream by 8fd4d993ca5c "Remove tests for the old analyzer" and no longer exists).
e Both directions demonstrated? Yes. Master binary: server dies, stack PlannerContext.h:115 / StorageDistributed.cpp:773 / :893 / InterpreterSelectQuery.cpp:3010 / ExecuteScalarSubqueriesVisitor.cpp:213, and the runner reports ClickHouse server died during test '05234_...'. The TTL ... WHERE arm was measured the same way in isolation: master dies with the identical stack continuing through TTLDescription.cpp:1270/:1490, the patched binary answers Code: 395 with max(__table1.id) in the message, proving the subquery really ran against the distributed source. Patched binary: [ OK ], then 50/50 randomized plus 50/50 plain. Each server's buildId() was matched to its binary before the run. Both parallel-replica arms were also run against mutant binaries carrying only the removal of the line each covers, and each reddens with CLUSTER_DOESNT_EXIST on its own arm and no other; the one added assertion that does not redden (create_table_query keeps the clause the user wrote) is invariance coverage and is labelled as such rather than counted. The session-level arm's redness is also independent of the runner's settings draw: it pins automatic_parallel_replicas_mode = 0 (its own default, which the runner otherwise sets to 2 with probability 0.25 and which would make the interpreter clear the feature itself), and the mutant reddens both with that value forced to 2 and with randomization off, while the same mutant passes if the pin is removed.
f Fix is general across code paths? Fixed in the producer rather than at the crash site, so every analyzer-only engine is covered at once rather than Distributed alone, and every caller of this producer at once rather than the reported one. That breadth is measured, not argued: the same crash was reached from a second, independent standalone-expression slot, a TTL ... WHERE predicate (TTLDescription.cpp:1490), which the one fix also resolves; both slots are now regression-tested.
g Fix generalizes across inputs (params/datatypes/wrappers)? The fault is a null pointer during planning, so it is type independent: the fuzzer's LowCardinality(UInt64) and a plain UInt64 behave the same. Both ways of naming the distributed source were measured, and they differ: a named Distributed table reaches the crash, while the remote(...) table function is rejected earlier with THERE_IS_NO_QUERY from a table-function-only frame on patched and unpatched builds alike, so the test names the source both ways across its arms. I also measured the neighbouring standalone-expression sites with an observable value, INSERT ... VALUES ((SELECT ... FROM remote(...))) and ALTER TABLE ... UPDATE ... = (SELECT ... FROM remote(...)): both already use the analyzer and print identical values before and after (1001, 2001). A column DEFAULT cannot contain a SELECT at all (Code: 116), and a TTL expiry expression rejects a subquery with Code: 36.
h Backward compatible? Yes. No setting added or changed, so no SettingsChangesHistory.cpp entry; no serialization, format or metadata change. Stored table definitions are untouched, only how an existing definition's subquery is analysed changes.
i Invariants and contracts preserved? The restored invariant is the one the crash site assumes: a SelectQueryInfo reaching IStorage::read() carries a query tree and a planner context. Four behaviours of the old interpreter are carried over deliberately: materialized-view source substitution (through the storage overload, so a scalar subquery compiled during a view push still reads the inserted block), the insertion-table structure-hint suppression (now in the subquery settings, since QueryAnalyzer reads it from the scope context), materialized-CTE population (forceMaterializeCTE()), and the global-versus-local scalar cache decision, which can now only move a scalar from the global cache to the local one, never the reverse.

Session id: cron:clickhouse-impl-slot-4:20260921-171700

@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [73fa0e3]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 3/6) FAIL Performance dashboard
lazy_final_early_exit_limit #0 FAIL dashboard

AI Review

Summary

This PR moves scalar subqueries in standalone expressions onto InterpreterSelectQueryAnalyzer, carries over the analyzer-specific safeguards around parallel replicas and materialized CTEs, and fills in a server-side client version when the surrounding context was never turned into a query context. I did not find a remaining code-level correctness issue in the current diff or a still-live prior thread that needs reopening; the only issue is a changelog-category mismatch.

PR Metadata
  • Changelog category should be Critical Bug Fix, not Bug Fix: this PR fixes a real server crash in stable releases, which matches the template's Critical Bug Fix (crash, data loss, RBAC) bucket.
  • Changelog entry is required for that category, and the current entry is specific and user-facing enough once the category is corrected.

Exact replacement:

### Changelog category (leave one):
- Critical Bug Fix (crash, data loss, RBAC)
Final Verdict

✅ No blocking code findings. Change the changelog category to Critical Bug Fix before merge.

LLVM Coverage Report

Measured on commit 73fa0e3.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.30% -0.10%

Changed lines: Changed C/C++ lines covered: 32/36 (88.89%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 73fa0e3a4433b85e0e1d4f2ff3fea78904553d9e was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Sep 21, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 21, 2026
A `CHECK` constraint and a `TTL` expression are analysed with the global
context - `StorageFactory` hands the storage `args.getContext()`, which never
went through `Context::makeQueryContext` and so carries a zero client version.
Reading a `Distributed` table from such a subquery therefore sends a shard
query with an unknown initiator version, and `RemoteQueryExecutor::sendQueryUnlocked`
rejects it:

    Sending a distributed query with unknown (zero) client version.
    The query context was not initialized as an initial query

Until the previous commit the same statement dereferenced a null
`query_info.planner_context` and killed the server, so this is the next
failure on the same path rather than a new one. This server is the real
initiator of the subquery, so fill in its own version, exactly as
`Context::makeQueryContext` does for the other server-initiated queries and
`DDLTaskBase::makeQueryContext` does for a replayed DDL.

The shard of `test_shard_localhost` is local, so `prefer_localhost_replica`
decides whether `RemoteQueryExecutor` is reached at all; the new test case
pins the network path. Found by `Stress test (arm_asan_ubsan, meta in keeper)`
of the private sync of this pull request (STID: 4148-3044).

`t_scalar_constraint_user` is now dropped as soon as the `DETACH`/`ATTACH`
check is done. A `remote(...)` subquery still cannot be analysed during the
asynchronous database load - `QueryAnalyzer::resolveTableFunction` needs a
query context and a loading table has none - so a stress-test restart taken
while that table exists fails to load it.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6d65f59

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
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) not from this diff: after the restart, AsyncLoader::worker logs Code: 70. DB::Exception: Cannot convert String to double: Cannot attach table test_1.t_pfl_05079 ... (s AggregateFunction(quantile('0.5'), Float64)). That table is left behind by the previous release's own copy of 05079_parse_aggregate_function_typed_param, because tests/docker_scripts/upgrade_runner.sh runs the stress phase against previous_release_repository/tests/queries and --upgrade-check implies --fake-drop, so the table survives into the upgrade restart. The older binary persisted the parameter as a String, and my merged #119810, which prints those parameters with types, is already present on this head (compare puts this head 1152 commits ahead of its merge commit fcbf73ea6f67 and 0 behind), so it cannot repair a name that an older binary wrote. Breadth: 4 rows on 4 distinct pull requests since 2026-09-21T23:34:59Z, 0 on true master. This diff only guards a null planner_context in buildQueryTreeDistributed, which no metadata parse reaches a fix task is moved to pending (investigating at full effort, fixing-PR link to follow on this PR)
Upgrade check (amd_release) / The mutation submitted before the upgrade was not finished by the new server (see mutation_across_upgrade.txt) same job, downstream of the row above: a load job that failed makes the check's own system.mutations probe throw, and the check reports the throw as an unfinished mutation. Breadth: 19 rows on 19 distinct pull requests in 30 days, 0 on true master, onset 2026-09-20T22:22:43Z #121315 (mine, open)
Mergeable Check, PR aggregator statuses mirroring the two rows above #121315 plus the fix task above

Gates (a) to (d): 0 of 176 check runs queued or running, Config Workflow, Style check and Finish Workflow all success, 23 min since the last job finished (anchor 2026-09-22T05:55:34Z), and every failing row above has an owner.

Session id: cron:our-pr-ci-monitor:20260922-060304

@alexey-milovidov

alexey-milovidov commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121418&sha=6d65f5936b09462cd8b3640348583ee081a97ab7&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.

Both rows of Upgrade check (amd_release) have one cause: the previous release's copy of 05079_parse_aggregate_function_typed_param leaves behind (under --fake-drop) a table typed AggregateFunction(quantile('0.5'), Float64), which the upgraded server refuses to load:

Code: 70. DB::Exception: Cannot convert String to double: Cannot attach table `test_1`.`t_pfl_05079` ... (`s` AggregateFunction(quantile('0.5'), Float64)) ENGINE = Memory. (CANNOT_CONVERT_TYPE)

That failed attach then makes the system.mutations probe throw, which is the second row (the mechanism described in #121484 and #121315). The same t_pfl_05079 failure hit #102065, #119304 and #121372 in the last two days, so it is not caused by this PR. Probably the same shape as #121484, for the previous release's 05079 instead of 05211.

Fix opened: #121506

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Upgrade check (amd_release) failure on this PR's head: #121506 (external, open), "Do not run the previous release's 05079 in the upgrade check".

That closes the owner column for the ledger line I left open above. Both rows from that job (Error message in clickhouse-server.log and The mutation submitted before the upgrade was not finished by the new server) come from the one cause: the previous release (v26.9.1.1629-stable) persists AggregateFunction(quantile('0.5'), Float64), --upgrade-check implies --fake-drop so the table survives into the restart, and the failed load job then makes every system.mutations read throw ASYNC_LOAD_WAIT_FAILED. Neither row is caused by this PR's diff.

Separately, the release branch itself still carries the producer bug, so I asked for v26.9-must-backport on the merged #119810: #119810 (comment)

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 91ecf88

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, and it passed on this
head, so every red line below carries a fixing-PR link.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 4/6) / index_bulk_filtering #2 3 too long, 1 slower; 1 confirmed regression(s) on the performance dashboard. The index_bulk_filtering fixture is bimodal, so a mode flip reads as a large slowdown on either binary #121260 (ours, open)
Mergeable Check aggregator mirroring the row above #121260 (ours, open)
PR aggregator mirroring the row above #121260 (ours, open)

This head is clean everywhere else: a CIDB scan scoped to 91ecf883479a returns zero
FAIL/ERROR rows, and the shard above is the only job whose check_status is not
success/skipped. The unstable rows on shards 2/6, 3/6, 5/6 and 6/6 sit on jobs that reported
success, so they are not failures to own. The Upgrade check (amd_release) reds that the previous
head carried are gone on this one.

Why #121260 and not the dashboard-gate fix #121090: this shard's own report does call
index_bulk_filtering #2 slower, so #121090 (which suppresses a shard only when its own report does
not) cannot filter it. The fixture is the cause, and #121260 pins it: it stops merges on both tables,
writes max_block_size out explicitly, and asserts 16 active parts, so query #2's table
(test_minmax_index) gets a fixed part layout instead of a merge-dependent one.

Not caused by this branch. index_bulk_filtering #2 came back slower on 24 distinct refs in the
last 7 days, including true master
(pull_request_number = 0 on both amd_release and
arm_release shards), so the mode flip is fleet-wide and independent of any diff.

Session id: cron:our-pr-ci-monitor:20260922-110203

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 24, 2026
Merged via the queue into ClickHouse:master with commit ddae061 Sep 24, 2026
174 of 176 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim Yes, tracked. Fix PR: #121952, opened 10:35 UTC, after that job started at 08:59 UTC, so master@29dde9d3 does not contain it yet.

That run died on t_scalar_constraint_pr__fuzz_3, an AST-fuzzer clone of a table from 05234_constraint_scalar_subquery_over_distributed, the test I added here. The stress profile enables ast_fuzzer_any_query (tests/docker_scripts/stress_tests.lib:211), so DDL is replayed too and the renamed clone is not covered by the test's own DROP TABLE. It survives to the post-run restart, where the asynchronous metadata load has no query context and cannot re-analyse the CHECK constraint, and with async_load_databases=0 that is fatal. #121952 pins ast_fuzzer_any_query = 0 in that file, which removes every leftover arm: with the stress fuzzer profile installed, the restart failed in 6 of 6 runs before the pin and came up with no leftover tables in 6 of 6 after it.

Two occurrences so far, both from before the pin: this master run and Stress test (arm_asan_ubsan) on #121831 at 07:14 UTC.

The loader-side gap itself is pre-existing and not remote-specific: any scalar subquery in a persisted CHECK fails to load the same way. @ alexey-milovidov measured that on this PR and ruled it belongs to #96886, so #121952 only stops my test from manufacturing such a table.

alexey-milovidov added a commit that referenced this pull request Sep 25, 2026
This branch rejects a scalar subquery in a `CHECK` constraint on `CREATE TABLE`,
so the master test `05234_constraint_scalar_subquery_over_distributed` (added by
#121418) cannot create its
constraint tables anymore. The `CHECK` cases now expect `BAD_ARGUMENTS`; the
`throwIf` probe also shows the remote subquery is not executed on the way. The
parallel-replica cases only guarded the execution of such a constraint's
subquery, which cannot happen now, so they are removed.

The `TTL DELETE WHERE` cases, including the one over the network with
`prefer_localhost_replica = 0`, stay unchanged: `TTLDescription` keeps the
legacy `TreeRewriter` path on this branch, same as on master.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=96886&sha=3e8f0c349a19f06d1da16b219d40abc10303c1c0&name_0=PR&name_1=Fast%20test
#96886

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request Sep 26, 2026
…queries-via-analyzer

Brings in #121418, which fixes the `AST fuzzer (amd_debug, targeted)` red
`Segmentation fault (STID: 3422-39ed)` on 983463d (the scalar-subquery producer through `ExecuteScalarSubqueriesVisitor`):
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121639&sha=983463d6ae29e47625c100c134e9f40c822a41e8&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
PR: #121639

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
alexey-milovidov added a commit to azat/ClickHouse that referenced this pull request Sep 28, 2026
…ottling

Pulls in ClickHouse#121418 (tsan segfault in `StorageDistributed::read` from a scalar subquery) and
the upgrade check recovery of read-only replicas that refuse `KILL MUTATION`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
raimannma pushed a commit to raimannma/ClickHouse that referenced this pull request Oct 1, 2026
… JOIN

A scalar subquery with a `JOIN` in a `TTL` expression crashes the server on `CREATE`
(`p` is a MergeTree table ordered by `k`):

    CREATE TABLE t (d DateTime, x UInt64) ENGINE = MergeTree ORDER BY tuple()
    TTL d + INTERVAL 1 YEAR WHERE x < (SELECT count() FROM db.p AS p, db.b AS b WHERE p.k = b.k);

with a null read in `buildRuntimeRangePredicate`. The same subquery in a `CHECK` constraint is
created fine, but loading the table afterwards (a restart or `ATTACH DATABASE`) aborts with
`Logical error: 'Query context is not available for __applyFilter'`, and so does a replica
applying `ALTER ... MODIFY TTL` of a `ReplicatedMergeTree`, from `ReplicatedMergeTreeQueue`.

Since ClickHouse#121418 `ExecuteScalarSubqueriesVisitor` plans such a subquery with
`InterpreterSelectQueryAnalyzer`, so its `JOIN` gets join runtime filters. They rendezvous through
a per-query `IRuntimeFilterLookup` that only `Context::makeQueryContext` creates: the index analysis
of the probe side reads the lookup of its read step's context, the build side and `__applyFilter`
read the query context of the current thread. A `TTL` expression (`registerStorageMergeTree`, and
`ReplicatedMergeTreeTableMetadata::Diff::getNewMetadata` on a replica) and a `CHECK` constraint of a
table being loaded (`DatabaseOnDisk`) are analysed with a copy of the global context, which is not a
query context, and the table loader and replication threads run no query. A `CHECK` constraint at
`CREATE` is fine because it is analysed with the context of the `CREATE` query.

The subquery keeps the context it is analysed with and gets what the join runtime filters need:
* a thread with no thread group is attached to a query by a `QueryScope`: the query of that
  context if it has one, otherwise a copy of the context made a query context. The scope is
  created before the interpreter, because the analyzer already executes nested scalar subqueries
  in its constructor, and `getQueryInterpreter` returns that query together with the interpreter,
  because every other reference to a query context is weak (`Context::query_context`,
  `ThreadGroup`) and it has to outlive the pipeline;
* it takes the filter lookup of the current thread's query context, the one the build side and
  `__applyFilter` use.
Each part is needed: without the lookup the `CREATE` crashes again, without the scope or without
keeping its query alive the load aborts again, and with the scope created only after the
interpreter a `JOIN` in a nested scalar subquery still aborts the load.

The analysis context itself is not made a query context: that would also make table functions
resolve in the subquery (`QueryAnalyzer::resolveTableFunction` needs a query context), and a table
function in such a subquery is still rejected with `THERE_IS_NO_QUERY`, as before.

26.8 and 26.9 run these subqueries with the old interpreter, without join runtime filters, so this
is master-only. Found in the review of ClickHouse#122390, which fixes the other producer of a plan without a
lookup, the dependency analysis of `CREATE`.

The new test has one arm per carrier: `TTL ... WHERE` at `CREATE`, `CHECK` at load, a `JOIN` only in
a nested scalar subquery of a `CHECK`, and a replicated `MODIFY TTL` in an `Atomic` and in a
`Replicated` database. Each arm alone kills or aborts the unfixed server. Two more arms check that a
table function in such a subquery is still rejected, and that at `CREATE` the `TTL` subquery built a
join runtime filter and the index analysis of its read used it (`RuntimeFiltersCreated`,
`RuntimeFilterGranulesConsidered`). There is no `TTL ... GROUP BY ... SET` arm: query parameters are
not substituted in its assignments, and a TTL is not analysed in the database of the statement.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit to valerypetrov/ClickHouse that referenced this pull request Oct 8, 2026
…e analyzer

A standalone expression - a row policy, a `CHECK` constraint, a `TTL` expression - is
compiled by `ExpressionAnalyzer`, and `ActionsMatcher::makeSet` built the plan of an `IN`
subquery in it with the interpreter that preceded the analyzer. `StorageDistributed`
resolves its read through a query tree and a planner context that interpreter never
builds, and dereferences them unconditionally, so reading a `Distributed` table from such
a subquery crashed the server.

`IInterpreterUnionOrSelectQuery` used to set `allow_experimental_analyzer = 0` on the
interpreter's own context, and the storages read under it took their AST arm. ClickHouse#120311
removed the assignment together with the arms it protected, which is what uncovered the
dereference. It is the same defect as
ClickHouse#121464, reached through a second producer:
ClickHouse#121418 replaces the one in
`ExecuteScalarSubqueriesVisitor`, which accounts for 27 of the 29 occurrences of the two
sibling STIDs in the CI database over the last five days; the other two come through
`interpretSubquery`, and the STID does not tell them apart because it is computed from the
top of the stack, which both share.

`makeSet` now builds the plan with `InterpreterSelectQueryAnalyzer`. What `interpretSubquery`
does around it - a table name or a table function becomes `SELECT <columns> FROM it`, and
the subquery gets its own context with the whole-query result limits lifted - is shared as
`prepareSubquery` rather than duplicated. `makeSet` already built a query tree of the same
subquery for its set key, so the analyzer was on this path before this change.

Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=e96f004b984ced9a97237e99b3e744599a917870&name_0=MasterCI&name_1=Stress%20test%20%28arm_tsan%29

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants