Skip to content

Do not extract a non-deterministic partial predicate below a join - #117249

Merged
alexey-milovidov merged 12 commits into
masterfrom
fix-join-disjunctions-push-down-nondeterministic
Sep 13, 2026
Merged

alexey-milovidov merged 12 commits into
masterfrom
fix-join-disjunctions-push-down-nondeterministic

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Closes: #116930
Related: #116939
Related: #116848
Related: #112700

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix a WebAssembly UDF not declared DETERMINISTIC being treated as deterministic within a query, which let query plan optimizations such as the default-enabled use_join_disjunctions_push_down clone its call below a join and silently drop rows.

Description

use_join_disjunctions_push_down extracts a per-side partial predicate and pushes it below the join
with addFilterOnTop, leaving the original filter in place. A conjunct that is not deterministic
within the query is therefore drawn twice per row, independently, and only a row passing both draws
survives.

The onlyDependsOnAvailableColumns determinism check that this pull request originally added has
since landed on master through #112700, in a stronger
form that also walks lambda bodies, so that hunk is dropped here and master is taken as is.

What remains is the other half of the same defect, which is not fixed by that check.
FunctionUserDefinedWasm only overrode isDeterministic, so a WebAssembly UDF created without
DETERMINISTIC inherited IFunction::isDeterministicInScopeOfQuery() == true and was still
classified as extractable — a module can keep state or read entropy, so this is wrong for every
optimization that relies on that predicate, not just this one. Executable UDFs already answer
false here unconditionally. The override now returns the UDF's declared determinism.

Tests:

  • 05144_join_disjunctions_push_down_nondeterministic pins the plan for rand, for a stateful
    predicate, and for the deterministic predicate that must still be pushed, plus the row-count band
    that regressed from ≈500000 to ≈250000.
  • 05145_join_disjunctions_push_down_wasm_udf creates the same WebAssembly UDF twice, once plain and
    once DETERMINISTIC, and asserts that only the latter is cloned below the join.

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

Version info

  • Merged into: 26.9.1.1421 (included in 26.9 and later)

`use_join_disjunctions_push_down` pushes a per-side partial predicate below the join and keeps
the original filter on top, so a non-deterministic expression is drawn twice per row,
independently: a row that satisfies the query's own filter can still be discarded by the
pre-filter's draw. With `WHERE (a = 1 AND rand() % 2 = 0) OR (a = 2)` the selection probability
for the `a = 1` rows silently dropped from 1/2 to 1/4.

Nothing else in `onlyDependsOnAvailableColumns` rejects such a function - a nullary `rand` has
no inputs, so it was trivially accepted. The main filter pushdown declines for the same reason.

Closes: #116930
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [af2dc38]

Summary: ✅


AI Review

Summary

This PR fixes the new analyzer / query-plan half of issue #116930 by making FunctionUserDefinedWasm report non-DETERMINISTIC UDFs as non-deterministic within a query and by adding plan-level regressions for join disjunction pushdown. I found one remaining correctness gap: the legacy AST predicate pushdown path still never resolves WASM UDFs, so with enable_analyzer = 0 it can keep duplicating a non-DETERMINISTIC WASM predicate across a subquery boundary and reproduce the same row-loss bug.

Findings

⚠️ Majors

  • [src/Functions/UserDefined/UserDefinedWebAssembly.cpp:524] The new trait fixes query-plan consumers, but ExtractExpressionInfoVisitor still checks only FunctionFactory::tryGet (src/Interpreters/ExtractExpressionInfoVisitor.cpp:49-58), so PredicateExpressionsOptimizer keeps treating LANGUAGE WASM UDFs as deterministic on the legacy path and PredicateRewriteVisitor::rewriteSubquery duplicates the predicate into the subquery HAVING while leaving the outer copy in place (src/Interpreters/PredicateExpressionsOptimizer.cpp:84-92, src/Interpreters/PredicateRewriteVisitor.cpp:214-217). A query such as SELECT ... FROM (subquery) WHERE wasm_nondet(x) % 2 = 0 SETTINGS enable_analyzer = 0, enable_optimize_predicate_expression = 1 can therefore still turn one draw into two independent draws and silently drop rows. Suggested fix: resolve WASM UDFs in ExtractExpressionInfoVisitor / hasNonRewritableFunction the same way ActionsVisitor and TreeOptimizer already do, and add a focused legacy regression.
Final Verdict

⚠️ Changes requested. The new analyzer path is covered, but the same non-deterministic WASM contract is still violated by the legacy AST predicate optimizer.

LLVM Coverage Report

Measured on commit af2dc38.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.40% 81.40% +0.00%

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

Full report · Diff report

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

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing af2dc385b with master c287fac2b (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.

Object file sizes

24 object files changed (+142.07 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/FillingStep.cpp.o 158.83 KiB 270.11 KiB +111.29 KiB (+70.07%)
src/CMakeFiles/dbms.dir/Core/SortDescription.cpp.o 204.89 KiB 221.96 KiB +17.07 KiB (+8.33%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@rschu1ze — tagging you on this one as JOIN-related, as requested. Review request sent too.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Approved.

@alexey-milovidov alexey-milovidov self-assigned this Aug 31, 2026
The AI review asked to reject `isStateful` functions in `onlyDependsOnAvailableColumns` as well.
Such a predicate cannot reach the extraction: `tryPushDownFilter` returns early when the filter
expression `hasStatefulFunctions`, so the partial-predicate path is never entered for it, and the
classic order-dependent stateful functions (`rowNumberInAllBlocks`, `blockNumber`,
`runningDifference`, `runningAccumulate`, `neighbor`, `generateSerialID`) additionally report
`isDeterministicInScopeOfQuery() == false` and are already rejected by this change.

Adding the check would therefore be unreachable code. Instead, note the upstream guard in the
comment and pin the behavior with a test: the plan for a filter holding a deterministic stateful
function (`timeSeriesTagsToGroup`) mentions it exactly once, so the predicate is not cloned below
the join.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6, 5/6, 6/6) and provide a fix in a separate PR. If the fix is already in progress, link it here.

All three shards report a job-level ERROR with the single entry Container memory budget exceeded (/docker) and no test results at all, so it is the CI container memory guard rather than anything this pull request touches (a query-plan optimizer change cannot affect the docker cgroup budget). I have merged master and pushed, so a fresh run will tell whether it persists.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

Confirmed, and your reading is right: this is the CI container-memory guard, not anything this pull request touches. On all three shards the guard ERROR is the only failing row in CIDB, and every pytest banner is clean: 2/6 1141 passed, 41 skipped, 1 xfailed in 5984.85s; 5/6 949 passed, 26 skipped in 5949.41s; 6/6 1189 passed, 23 skipped in 6029.54s. Zero failed anywhere, so each shard did the work and then lost the result.

The arm, read from the jobs and not from the clock: all three printed Merge 8a085101... into ac95bf3cf20cdb4f08660d2b7dd27f915cd5abd0, and that base (2026-08-31T01:49:03Z) is a strict ancestor of both fix merges (ahead_by=0, behind_by 129 and 604), so it carried neither. Their own env agrees, CI_DIND_INIT_RESERVE=17179869184. Your new head 46b9fc8b carries both.

Owners, split by the kernel record's victim rather than by shard (all oom_memcg=/docker/<dind>/docker):

Live rates since 2026-09-02T00:00Z, trees carrying the guard row over trees: 1/6 0/559, 2/6 1/559, 3/6 0/555, 4/6 0/559, 5/6 1/558, 6/6 98/556 = 17.6%. Both non-6/6 hits are one unrelated tree (69550e07) built on the same ac95bf3c base as yours, CI_DIND_INIT_RESERVE=17179869184, all victims task=gdb, so on trees that actually carry your two fixes 2/6 and 5/6 are at zero. 6/6 is not: its three most recent hits all report CI_DIND_INIT_RESERVE=8589934592, all three carry task=clickhouse victims (one of them 3 of 3, no gdb at all), and all three ran the two session-scoped fixture modules. That is the residual #117564 targets. It converts those three modules to module scope, so it does not remove every long-lived container.

No old-analyzer shard has been scheduled on 46b9fc8b yet, its CI is still in the build stage.

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
…inistic in scope of query

A WASM UDF declared without `DETERMINISTIC` only overrode `isDeterministic`, so it
inherited `IFunction::isDeterministicInScopeOfQuery() == true`. Query plan optimizations
that only consult the query-scope answer - including the join disjunctions push-down guard
added by this pull request - could therefore duplicate such a call and evaluate it
independently above and below a join. `Executable` UDFs already answer `false` here.
Master took 05069 for `05069_wasm_abi_buffered_constant_argument_cut`, so the test moves to
05144.

The old test only compared result counts with `use_join_disjunctions_push_down` on and off, so
it would have kept passing if `tryToExtractPartialPredicate` had stopped extracting anything at
all. It now asserts the plan: with a disjunction whose branches touch both sides of the join,
enabling the setting adds one pre-filter per side below the join and disabling it leaves only the
filter above the join. Adding a `rand` conjunct keeps both pre-filters but leaves `rand` out of
them, and a stateful conjunct suppresses extraction entirely.

The stateful check no longer counts occurrences of the function name in a plain `EXPLAIN` - that
count was 2 rather than 1 under parallel replicas, which is what made the test red in the
`ParallelReplicas` stateless run, and 0 with `explain_query_plan_default = legacy`.

`05145_join_disjunctions_push_down_wasm_udf` covers the WASM UDF case: a UDF declared without
`DETERMINISTIC` is left in the filter above the join, while a `DETERMINISTIC` one is extracted
into the pre-filter below it.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117249&sha=6a6c9aad282ec8499f6024114a9d19463ea715bf&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

It is a TLP Aggregate oracle mismatch on a query with no join at all, so it cannot involve this pull request (which only touches the join disjunctions push-down and WASM UDF determinism):

SELECT count() IGNORE NULLS FROM t_null_const_set_index__fuzz_0 STREAM BOUNDED CURSOR {'all': {'block_number': 2}}
WHERE xor(v IS DISTINCT FROM 1023, (nullIf(65535, 7) AND firstNonDefault(65537) AND (v = 9223372036854775806)))

The suspicious ingredients are firstNonDefault in a boolean AND chain together with a streaming STREAM BOUNDED CURSOR read. I could not find an existing open issue for it.

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator

The fix is already in progress: #117188, still open and with no review yet. It is the same defect you asked me about on #112968, where I linked it on 2026-08-30: #112968 (comment)

firstNonDefault is not involved. The report's own reproducer shows the two compared sides are not the query you quoted: the reference carries no predicate at all, and only the three arms do.

Reference:   SELECT count() IGNORE NULLS FROM t_null_const_set_index__fuzz_0 STREAM BOUNDED CURSOR {'all': {'block_number': 2}}
Metamorphic: countMerge over countState() with WHERE p / WHERE not(p) / WHERE isNull(p), same cursor

Only a bare count() is eligible for the implicit min-max/count projection, and canUseProjectionForReadingStep never tested for a streaming read, so the reference is answered from part metadata and drops the CURSOR bound, while the three predicate-carrying arms read through the streaming reader.

Measured on master e568d262, 100 rows in three blocks, same cursor:

query result
reference, bare count() 100, the whole table
the three-arm countMerge 60
reference with optimize_use_implicit_projections = 0 60
countIf(1), ineligible for the shortcut 60

EXPLAIN of the reference is ReadFromPreparedSource (_minmax_count_projection) by default and ReadFromMergeTree with that setting off, which is the plan the guard in #117188 leaves in place.

Two measurements clear the ingredients you suspected. Without STREAM, the same xor(v IS DISTINCT FROM 1023, (nullIf(65535, 7) AND firstNonDefault(65537) AND ...)) gives 100 for the whole table and 100 for the three-arm sum, so the ternary partition is sound. And the master run at 58f74d47 today hit the same family with no IGNORE NULLS, no firstNonDefault and no nullIf, just WHERE p.x = 65535.

Worth flagging because it changes the urgency: this is no longer pull-request-only. Over 30 days that job has 66 job-level errors across 64 distinct pull requests against 2700 successes, and two are true master runs, both within the last 48 hours (590458213b 2026-09-06 19:21Z and 58f74d4731 today 12:35Z).

So nothing separate is owed here. #117188 is one guard line plus its regression test.

alexey-milovidov and others added 2 commits September 12, 2026 01:30
…ns-push-down-nondeterministic

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/partialJoinFilterPushDown.cpp
`05145_join_disjunctions_push_down_wasm_udf` failed in every sequential and flaky
check job: the `deterministic plan` block printed the same three lines in a
different order, with the extracted pre-filter below the join coming after the
`PREWHERE` step instead of before it.

The order in which a plan prints the filter above the join, the per-side
pre-filters below it and the `PREWHERE` steps depends on which side the join is
read from, and the settings randomizer is free to flip that. The assertion is
about which filter lines exist, not about their order, so sort them with
`ORDER BY 1`. The same is applied to `05144_join_disjunctions_push_down_nondeterministic`,
whose blocks have the same shape.

The references are unchanged: the lines were already in sorted order.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master (2583 commits behind) and resolved the conflict in src/Processors/QueryPlan/Optimizations/partialJoinFilterPushDown.cpp.

The determinism check this pull request added to onlyDependsOnAvailableColumns has landed on master in the meantime via #112700, in a stronger form that walks lambda bodies with allNodeFunctions rather than testing node.function_base only. I took master's version wholesale and dropped my hunk. The pull request description is updated accordingly.

What is still only here is the other half of the same defect, which that check does not cover: FunctionUserDefinedWasm overrode isDeterministic but not isDeterministicInScopeOfQuery, so a WebAssembly UDF created without DETERMINISTIC inherited IFunction's true and stayed extractable. Plus the two tests.

I also fixed the real red on the previous run. 05145_join_disjunctions_push_down_wasm_udf failed in every sequential and flaky-check job with the same three deterministic plan lines in a different order — the extracted pre-filter printed after the PREWHERE step instead of before it. The order in which the plan prints the filter above the join, the per-side pre-filters and the PREWHERE steps depends on which side the join is read from, which the settings randomizer flips. The assertion is about which lines exist, so both tests now sort them with ORDER BY 1; the references are unchanged because the lines were already in sorted byte order. Verified locally against a private server: both tests pass, three consecutive runs with randomized settings.

The stress-test Cannot start clickhouse-server red was the fsdb_05057_file_rename_after_processing_write_grant_* Filesystem database whose directory was gone; that is fixed on master by 3534c14829bc and is pulled in by this merge.

@groeneai, investigate the remaining two failures and provide a fix in a separate pull request; if a fix is already in progress, link it here. Both are in Stateless tests (arm_asan_ubsan, azure, sequential) and both are about distributed-plan task scheduling, which this pull request does not touch:

  • 04648_distributed_plan_task_error_propagation — labelled flaky, failed 0 out of 3 reruns. Expected CANNOT_SCHEDULE_TASK (439) but got POCO_EXCEPTION (1000): Failed to receive final_result__0_0 from 127.0.0.1:9223, peer closed connection. The peer died before the scheduling error could be propagated, so the test races the error path it means to assert.
  • 04340_distributed_plan_status_reenqueue_fault

I could not find an open issue for either.

@groeneai

Copy link
Copy Markdown
Collaborator

No separate pull request is owed: both are fixed by #118390, merged 2026-09-09 05:40:05Z as 129e4b59.

The report you linked ran without that fix. compare/129e4b59...15abb685 gives behind_by=986, while your master merge in this pull request, 94c64a1b, gives behind_by=0, so the next run of that job should be clean.

The two are one bug. 04648 runs about 8.5 minutes before 04340 in the same sequential job, and pre-fix it aborted the client with return code 232 (the 439 vs 1000 mismatch you quoted) before reaching its SYSTEM DISABLE FAILPOINT line, leaving distributed_plan_record_failure_while_starting_tasks armed as REGULAR and starving 04340's own fault path. #118390 fixes the propagation and makes that failpoint ONCE. Since the merge: 10462 OK / 5 FAIL for 04648 and 9765 OK / 3 FAIL for 04340, with zero failures on master (1403 and 1399 OK). Of those 8 residual failures, 7 are on heads that do not contain 129e4b59; the 8th is unrelated, Unrecognized option '--query_plan_derive_not_null_filters_from_joins' from that pull request's own diff. Full measurement: #117803 (comment)

On the missing issue: three exist and all are closed, which is why the search came up empty. #118626 (yours, closed as completed on 2026-09-08, about 20 hours before the fix actually merged), #118831 and #118832 (closed as not planned).

What is still open is the generic guard rather than this pair: #105942 resets enabled failpoints in clickhouse-test after no-parallel tests, so a test that dies before its own disable line cannot poison the next one.

@clickhouse-gh clickhouse-gh Bot added comp-udf User-defined functions (SQL UDFs, executable UDFs) and UDF framework. and removed comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Sep 12, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master again (232 commits behind) — a clean merge, no conflicts. Rebuilt and re-ran the tests against the merged tree on a private server: 05144_join_disjunctions_push_down_nondeterministic and 05145_join_disjunctions_push_down_wasm_udf both pass, as do all 50 tests of the surrounding wasm and disjunctions-push-down families. The diff against master is still only the FunctionUserDefinedWasm::isDeterministicInScopeOfQuery override plus the two tests.

The sole remaining red, Upgrade check (amd_release), is not caused by this pull request and a fix is already in progress — #113983, open since 2026-08-08.

The single log line the check trips on is

<Error> StorageFileLog (test_1.filelog_bad_path_attach): The absolute data path should be inside `user_files_path`(/var/lib/clickhouse/user_files/)

That table belongs to 04202_filelog_attach_path_outside_user_files, which exists on master and exercises the LOG_ERROR(...); return; branch of the StorageFileLog constructor on purpose: an ATTACH with a path outside user_files_path is supposed to log and continue rather than throw. The error is therefore expected output of a master test, and #113983 adds it to the upgrade check allowlist. A query plan optimizer change plus a WebAssembly UDF determinism flag cannot produce a StorageFileLog path diagnostic.

It is also rare rather than fleet-wide, which is why it had not surfaced here before. Over the last 30 days CIDB has exactly two occurrences of that message in Error message in clickhouse-server.log, on two unrelated trees:

pull request started commit
117249 2026-09-12 04:40:51 94c64a1b
115346 2026-09-11 00:31:28 bd5dcfe1

@groeneai, nothing separate is owed here as far as I can tell — but #113983 has been open for a month with no review, so if you can get it moving that would close this class of red for good.

Thanks for the two answers above; both are settled. #118390 (merged 129e4b59) covers 04648_distributed_plan_task_error_propagation and 04340_distributed_plan_status_reenqueue_fault, and this branch now carries it.

@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed, and nothing separate is owed here. #113983 is the fix for that red, and your reading of it matches what I measured: the LOG_ERROR(...); return; reattach branch of 04202_filelog_attach_path_outside_user_files, 2 occurrences in 30 days, 0 on master.

I have merged master into it and pushed f996ddf8. It was 17,164 commits behind at that point, the merge was clean, and CI is running again on the new head (the previous run was green, but it dates from 2026-08-13). The diff against master is unchanged at one file, +7/-0 in tests/docker_scripts/upgrade_runner.sh: a single allowlist entry anchored as StorageFileLog (.*\.filelog_bad_path_attach): The absolute data path should be inside, so any other StorageFileLog error still surfaces. Allowlist census is 121 patterns on master and 122 on the merged branch, with none of master's lost.

The reason it stalled is that no review was ever requested on it: the only solicitation was a cc to @ leshikus at publication, which got no reply, and it has had no human review or comment in 35 days. Approving it once the run is green, or naming the reviewer you would rather have look at it, is the one step I cannot take myself.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master again (174 commits behind) — a clean merge, no conflicts, pushed as 2d64288e7234. The diff against master is unchanged: the FunctionUserDefinedWasm::isDeterministicInScopeOfQuery override plus the two tests. src/Functions/UserDefined/UserDefinedWebAssembly.cpp recompiles clean on the merged tree; IFunction::isDeterministicInScopeOfQuery is untouched by the merged range, so the override still binds.

The CH Inc sync red was not this pull request. It was reported as build failed, but the private sync PR never got to a build: its Style check failed on ruff with

ci/workflows/auto_releases.py:59:5: invalid-syntax: Duplicate keyword argument "engine"
ci/workflows/create_release.py:25:5: invalid-syntax: Duplicate keyword argument "engine"
ci/workflows/nightly_cloud_api_docs.py:14:5: invalid-syntax: Duplicate keyword argument "engine"
ci/workflows/sync_silk.py:8:5: invalid-syntax: Duplicate keyword argument "engine"
ci/workflows/weekly_cfi.py:29:5: invalid-syntax: Duplicate keyword argument "engine"

which dropped all 20 downstream jobs. That is a private-master defect of the day — engine=Workflow.Engine.GH_ACTIONS written twice in five workflow definitions — and it is already fixed on private master. The sync run had simply started against the broken merge base. I merged current private master into the sync branch (clean), so the next run uses the fixed base.

The one remaining public red is Stress test (arm_tsan), and it is a parallel replicas coordinator exception:

Logical error: 'Initiator received more initial requests than there are replicas: replica_num=1'
DB::ParallelReplicasReadingCoordinator::ImplInterface::handleInitialAllRangesAnnouncement
  <- DB::RemoteQueryExecutor::processMergeTreeInitialReadAnnouncement
  <- DB::DDLWorker::processTask <- DB::DatabaseReplicatedDDLWorker::tryEnqueueAndExecuteEntry
  <- DB::InterpreterCreateQuery::createTable

i.e. a CREATE TABLE replayed through the Replicated database DDL worker whose query reads with parallel replicas, where the coordinator receives more announcements than replicas_count. This pull request adds a determinism flag to WebAssembly UDFs and two tests; it touches neither the coordinator, the DDL worker, nor the announcement path.

It is also fleet-wide rather than specific to this branch. Over the last 30 days CIDB has 20 occurrences of that message, across 20 distinct pull requests and 7 different job flavours (Stress test on arm_tsan, amd_tsan, arm_debug, arm_release, arm_msan, arm_asan_ubsan, s3, plus one AST fuzzer), from 2026-08-18 to today — including one run on master itself (82cfa6a4, 2026-08-26, Stress test (arm_release)).

@groeneai, investigate this one and provide a fix in a separate pull request; if a fix is already in progress, link it here. I could not find an open issue — the only matching ones are closed and old (#65043, from 2024).

On #113983: thank you for merging master into it and getting a fresh run going. Since the change is one allowlist line in tests/docker_scripts/upgrade_runner.sh, the right reviewer is whoever owns the upgrade check rather than StorageFileLog — please request review from the CI maintainers on the pull request itself (a cc in the body is not a review request and does not show up in anyone's queue, which is exactly why it sat for 35 days). I will look at it as well once its run is green.

@groeneai

Copy link
Copy Markdown
Collaborator

A fix is already open: #115786 ("Do not run the server-side AST fuzzer on a collaborative worker context"), open since 2026-08-21, no review on it yet.

Mechanism, measured on this run's artifacts (5a97fe54, Stress test (arm_tsan)): stress runs write ast_fuzzer_runs=5 and ast_fuzzer_any_query=true into the default profile server-wide (tests/docker_scripts/stress_tests.lib), so the server-side fuzzer also fires on a query the node received as a parallel replicas worker. The fuzz context copies client info, so it keeps that worker's number_of_current_replica and merge_tree_all_ranges_callback, and the fuzzed copy announces a second time under the borrowed replica number.

The chain from clickhouse-server.stress.log, test 04649_atomic_populate_materialized_view_query_local_parallel_replicas (query text and part ranges abridged):

16:26:41.637 {a63ded3c} ParallelReplicasReadingCoordinator: Creating parallel replicas coordinator with replicas_count=3
16:26:41.655 {b09f6ed6} executeQuery: (from [::ffff:127.0.0.1]:50730, initial_query_id: a63ded3c) INSERT INTO test_2.mv SELECT ... FROM test_2.src
16:26:41.674 {a63ded3c} DefaultCoordinator(test_2.src): Response ranges for replica 1: 3 parts: [all_1_1_0, all_3_3_0, all_4_4_0]
16:26:41.674 {b09f6ed6} MergeTreeReadPoolParallelReplicas: Response ranges: 3 parts: [all_1_1_0, all_3_3_0, all_4_4_0]
16:26:41.696 {b09f6ed6} executeQuery: Read 3000 rows, 29.29 KiB in 0.042 sec.
16:26:41.698 {b09f6ed6} ASTFuzzer: Fuzzed query: INSERT INTO test_2.mv SETTINGS ... SELECT __table1.id AS id FROM test_2.src ...
16:26:41.700 {f2b391da} executeQuery: (internal) INSERT INTO test_2.mv SETTINGS ...
16:26:41.709 {f2b391da} MergeTreeReadPoolParallelReplicas: Chosen segment size: 128
16:26:41.709 {a63ded3c} Logical error: 'Initiator received more initial requests than there are replicas: replica_num=1'

Lines 3 and 4 identify b09f6ed6 as replica 1 of the initiator's read. The fuzzer fires on it after its read finishes, on the same thread and under the same query id, and the fuzzed copy f2b391da re-enters the follower read pool 11 ms later. Initial requests reach the coordinator as replica 1, replica 2, replica 0, then replica 1 again, so the fourth trips the check against replicas_count = 3.

The frames in the stack are the initiator side, so they name whichever query happened to initiate that read, here a CREATE MATERIALIZED VIEW ... POPULATE replayed by the Replicated database DDL worker. The defect is on the worker side, which is why the signature spans job flavours and branches, master included, and why nothing in the coordinator, the DDL worker or the announcement path needs to change. #115786 returns early from executeASTFuzzerQueries when getClientInfo().collaborate_with_initiator is set, which is precisely the condition the follower read pool requires (Context::canUseParallelReplicasOnFollower), so it suppresses the fuzz run that produced the extra announcement.

There is no open issue and I have not opened one; #115786 is the only tracking artifact today. I can file one if you want the signature tracked separately from the fix.

@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

This PR only changes how a WebAssembly UDF reports its query-scope determinism (so a non-DETERMINISTIC WASM UDF is no longer cloned below a join by use_join_disjunctions_push_down), plus two new stateless tests. None of the ClickBench queries use a join or a WASM UDF. The two flagged queries (Q28 and Q34) are single-table GROUP BY aggregations that cannot execute the changed code path, so their ~5% deltas are run-to-run variance, not a PR effect — Q28 is additionally an intrinsically noisy query. Q34's within-envelope suppression is consistent with the diff and stands.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1105 1047 -5.2% <0.0001 aggregation: Q28 is a single-table GROUP BY on hits with no join and no UDF; this PR only changes WASM-UDF determinism and adds tests, so it cannot touch this path. The delta is run-to-run variance on an intrinsically noisy query.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 63f46866-75fd-47b1-a505-7630f9807921
  • MIRAI run: a93ba2f4-3aee-4dba-a6f8-e89f845bbe20
  • PR check IDs:
    • clickbench_24178_1789316770
    • clickbench_24363_1789316779
    • clickbench_24481_1789316793
    • tpch_adapted_1_official_24495_1789316794
    • tpch_adapted_1_official_24684_1789316798
    • tpch_adapted_1_official_24839_1789316974

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks — the mechanism you traced (the server-side AST fuzzer firing on a query the node received as a parallel replicas worker, and the fuzzed copy announcing a second time under the borrowed replica number) explains why the signature spans job flavours and master, and why the stack names whichever query happened to initiate the read. #115786 is the right fix; no separate issue is needed while that pull request is the tracking artifact.

On the latest run (2d64288e7234) every job is green — stress, upgrade, fuzzers, sync included. The only red is Fast test (arm_darwin), which the runner cancelled five minutes into a passing run (23/14939 tests in, all OK), so the workflow was marked FAIL without a single failing check. Nothing to fix in this branch; I merged master again (619 commits behind, clean, no conflicts, pushed as af2dc385bf94) to get a fresh run. The diff against master is unchanged: the FunctionUserDefinedWasm::isDeterministicInScopeOfQuery override plus the two tests. src/Functions/UserDefined/UserDefinedWebAssembly.cpp compiles clean on the merged tree; the merged range only adds an unrelated hasObservableSideEffects virtual to IFunction, so the override still binds.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 13, 2026
Merged via the queue into master with commit 4e8f2df Sep 13, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-join-disjunctions-push-down-nondeterministic branch September 13, 2026 20:25
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 13, 2026
pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Sep 27, 2026
…down respects their determinism

`ExpressionInfoVisitor` only consulted `FunctionFactory`, so an `EXECUTABLE` or `WASM` user-defined
function looked like an unknown function and was treated as deterministic. With `enable_analyzer = 0`
and `enable_optimize_predicate_expression = 1`, `PredicateExpressionsOptimizer` then duplicated a
predicate calling a non-`DETERMINISTIC` UDF into the subquery `HAVING` while keeping the outer copy,
evaluating it twice per row and silently dropping rows, the same pattern ClickHouse#117249 fixed for the
query-plan join disjunctions push-down.

Resolve user-defined functions through `UserDefinedExecutableFunctionFactory` and
`UserDefinedWebAssemblyFunctionFactory` first, the way `ActionsVisitor` and `TreeOptimizer` do.

Follow-up to the review of ClickHouse#117249

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-udf User-defined functions (SQL UDFs, executable UDFs) and UDF framework. 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

4 participants